java


How can 2 threads access a synchronized block at the same time?


Can you describe how in a multithreaded environment, the below code works incorrectly? I took the code from https://www.javacodegeeks.com/2014/11/multithreading-concurrency-interview-questions-answers.html. The description says 2 threads may enter the 2nd synchronized block one after the other. How can this happen? What is the relation by having 2 synchronized blocks?
public Integer getNextInt() {
Integer retVal = null;
synchronized (queue) {
try {
while (queue.isEmpty()) {
queue.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (queue) {
retVal = queue.poll();
if (retVal == null) {
System.err.println("retVal is null");
throw new IllegalStateException();
}
}
return retVal;
}
It's pretty simple - the first synchronized block (S1) makes a thread wait until the queue becomes non-empty. The second synchronized block (S2) makes a single thread take an item from the queue.
Thread 1 enters S1.
Thread 1 exists S1 -> queue is not empty
Thread 2 enters S1
Thread 2 exists S1 -> queue is still not empty
Thread 1 enters S2 -> takes an item from the queue and it becomes empty
Thread 1 exists S2
Thread 2 enters S2 -> attempts to take an element from the queue, but it's empty -> the exception is thrown.
As you can see, only 1 thread enters a synchronized block as expected, but this does not guarantee proper synchronization.
The whole point of using a synchronized block is to create a "transaction" around pieces of code that must be executed together; without the chance of another thread coming in "in between".
Your example has two blocks; and it is very well possible that a first thread leaves the first block; but a second thread kicks in before the first thread can enter the second block.
That is all there is to this.

Related Links

Java data transaction performance
One Scanner object not detecting anything in a file written to within the program
While loop with two queues Java
Use reflection to get the name of the method I'm in and the parameters passed to it?
How to pass object by socket in java Server Client
Spring JPA error: A JTA EntityManager cannot use getTransaction()
i have this error Exception in thread “AWT-EventQueue-0” [duplicate]
A method uses an array and returns an array, but I am using an array list
How to produce a line chart from ArrayList in Java
HTTP request to local server from Android device
Simple JSP + PI4J - GPIO Pins (several) Already Exists
Copying one enum to other java
checked out cucumber project with weird eclipse compilation error
Running jnml results in Error: Could not find or load main class org.neuroml.JNeuroML
Modify the program to accept a telephone number with any number of letters.
Compress Image cause Error in Android

Categories

HOME
osgi
image
date
clips
omnet++
push-notification
google-api-php-client
react-virtualized
syntax
grep
programming-languages
retrofit
ios-charts
bs4
apache-cayenne
jplayer
moonmail
ups
clearcase-ucm
jsdoc
solaris-10
swiftlint
dcevm
kvc
tibco-mdm
devops
format-specifiers
trading
info.plist
webkitspeechrecognition
data-manipulation
scorm2004
hybridauth
wallpaper
nssegmentedcontrol
ios5
jquery-bootgrid
neuroscience
libvpx
withings
service-discovery
ssjs
splice
sql-server-agent
flashair
fault
apache-fop
pango
multipeer-connectivity
rails-routing
dotnetzip
togetherjs
yii2-extension
pdfclown
angular-strap
android-textview
azure-virtual-network
google-web-starter-kit
mongocsharpdriver
persist
react-native-listview
prettytensor
sdf
itextpdf
iiviewdeckcontroller
web-controls
formatjs
modalpopup
codeigniter-url
tt-news
google-reader
uitouch
elliptic-curve
funcunit
valuechangelistener
bundles
tidy
batterylevel
gridcontrol
padarn
hosts-file
parametric-equations
jquery-ui-layout
cufon
mod-auth
invite
oncheckedchanged
yslow
google-friend-connect
mirah
microsoft-virtualization
sustainable-pace

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App