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

jsp - error for not correctly use JSTL
Android application displays black screen after running
JComboBox from ArrayList<String> - Not working - Java Swing
Issue with MySql Unique key
Parallel sort of generic linked list
Format a string containing no spaces using java [closed]
Beginner Programmer: Java String Manipulation
Implementing findOne in Spring Data (MongoDB)
My Asyntask is not working when I put it inside a separate java file
Create a variable having name stored in a string variable
WAR directory structure for Spring MVC JSP app?
Clicking back button causes force close / NullPointerException
How to add C++ “int” to HashSet<Integer>?
Time since first boot up
HeadlessException in my amazon ec2 instance
Netbeans 8.0 Unsupported major.minor version 52.0 error

Categories

HOME
testing
wso2
gerrit
keras
urbancode
gremlin
rsyslog
jira
cakephp-2.5
jpeg
win32gui
blueprintjs
ojdbc
opengl-es-2.0
azure-media-services
swagger-ui
pheatmap
add
windows-10-universal
export-to-csv
collectd
phaser
django-simple-history
pugjs
solaris-10
opencover
jasonette
intentfilter
orleans
realex-payments-api
wijmo
fish
cas
underflow
entitlements
fluentvalidation
buck
file-rename
newline
fabric8
iframe-resizer
jspresso
lxd
form-data
amazon-kinesis-kpl
normal-distribution
dartium
web-mining
hot-module-replacement
hockeyapp
android-browser
abstract-class
az-application-insights
reportbuilder
tasker
awt
estimote
bootstrap-dialog
heightmap
thin
google-datalayer
scrollable
parentheses
clean-architecture
dandelion
return-value
integrity
np-complete
media-player
python-cryptography
flutterwave
sonarlint-vs
yt-project
google-feed-api
grails-tomcat-plugin
infix-notation
bonobo
azure-virtual-network
login-control
simplewebrtc
prettytensor
hover-over
sdf
xpath-1.0
freelancer.com-api
separator
libressl
dukescript
drawbitmap
php-ci
jsapi
system.reflection
facebook-graph-api-v2.4
clicktag
angularjs-ng-click
file-copying
starcluster
jquery-layout
datagridviewcolumn
app42
prettify
pyhdf
gridcontrol
mylyn
bluepill
datawindow
boost-filesystem
jmock
suppress
jquery-ui-droppable
web-architecture
kdbg
photoshop-cs4
avatar
sector
django-notification

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