java


volatile vs not volatile


Let's consider the following piece of code in Java
int x = 0;
int who = 1
Thread #1:
(1) x++;
(2) who = 2;
Thread #2
while(who == 1);
x++;
print x; ( the value should be equal to 2 but, perhaps, it is not* )
(I don't know Java memory models- let assume that it is strong memory model- I mean: (1) and (2) will be doesn't swapped)
Java memory model guarantees that access/store to the 32 bit variables is atomic so our program is safe. But, nevertheless we should use a attribute volatile because *. The value of x may be equal to 1 because x can be kept in register when Thread#2 read it. To resolve it we should make the x variable volatile. It is clear.
But, what about that situation:
int x = 0;
mutex m; ( just any mutex)
Thread #1:
mutex.lock()
x++;
mutex.unlock()
Thread #2
mutex.lock()
x++;
print x; // the value is always 2, why**?
mutex.unlock()
The value of x is always 2 though we don't make it volatile. Do I correctly understand that locking/unlocking mutex is connected with inserting memory barriers?
I'll try to tackle this. The Java memory model is kind of involved and hard to contain in a single StackOverflow post. Please refer to Brian Goetz's Java Concurrency in Practice for the full story.
The value of x is always 2 though we don't make it volatile. Do I correctly understand that locking/unlocking mutex is connected with inserting memory barriers?
First if you want to understand the Java memory model, it's always Chapter 17 of the spec you want to read through.
That spec says:
An unlock on a monitor happens-before every subsequent lock on that monitor.
So yes, there's a memory visibility event at the unlock of your monitor. (I assume by "mutex" you mean monitor. Most of the locks and other classes in the java.utils.concurrent package also have happens-before semantics, check the documentation.)
Happens-before is what Java means when it guarantees not just that the events are ordered, but also that memory visibility is guaranteed.
We say that a read r of a variable v is allowed to observe a write w
to v if, in the happens-before partial order of the execution trace:
r is not ordered before w (i.e., it is not the case that
hb(r, w)), and
there is no intervening write w' to v (i.e. no write w' to v such
that hb(w, w') and hb(w', r)).
Informally, a read r is allowed to see the result of a write w if there
is no happens-before ordering to prevent that read.
This is all from 17.4.5. It's a little confusing to read through, but the info is all there if you do read through it.
Let's go over some things. The following statement is true: Java memory model guarantees that access/store to the 32 bit variables is atomic. However, it does not follow that the first pseudoprogram you listed is safe. Simply because two statements are ordered syntactically does not mean that the visibility of their updates are also so ordered as viewed by other threads. Thread #2 may see the update caused by who=2 before the increment in x is visible. Making x volatile would still not make the program correct. Instead, making the variable 'who' voliatile would make the program correct. That is because volatile interacts with the java memory model in specific ways.
I feel like there is some notion of 'writing back to main memory' at the core of a common sense understanding of volatile which is incorrect. Volatile does not write back the value to main memory in Java. What reading from and writing to a volatile variable does is create what's called a happens-before relationship. When thread #1 writes to a volatile variable you're creating a relationship that ensures that any other threads #2 viewing that volatile variable will also be able to 'view' all the actions thread #1 has taken before that. In your example that means making 'who' volatile. By writing the value 2 to 'who' you are creating a happens-before relationship so that when thread #2 views who=2 it will similarly see an updated version of x.
In your second example (assuming you meant to have the 'who' variable too) the mutex unlocking creates a happens-before relationship as I specified above. Since that means other threads viewing the unlock of the mutex (ie. they are able to lock it themselves) they will see the updated version of x.

Related Links

Java socket using wireshark fetch packets
Remote EJB 3.0 lookup (STS 3.4.0, Weblogic 10.3.5)
Error: Main method not found in class Binary, please define the main method as: public static void main(String[] args)
Interact with linux server using java JSCH
Using java.lang.String.format() to pad a string with given character
incompatible types int need string
Using trust manager for accepting self signed certificates in java
Using .png as label icon
SpringMVC-FileUpload - The request sent by the client was syntactically incorrect
Tomcat v7.0 server unable to start
Java Restful Webservices giving error
Android Google Map error android.view.InflateException: Binary XML file line #6: error initiating class fragment
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException [NetBeans]
Is there an annotation processor to enforce module visibility rules?
cannot find symbol getServletContext() error in upload file on server using servlet and html
How to override a specific value of log4j.properties?

Categories

HOME
image
listview
grep
yarn
twitter-bootstrap-4
c#-2.0
ckeditor
datastax-java-driver
bs4
add
synchronization
dtrace
uitypeeditor
jsdoc
aurigma
undefined
flux
scriptcs
cloudhub
extjs5
rundeck
crosstab
su
ping
google-cloud-nl
bcd
javascriptcore
iframe-resizer
phonegap
http-referer
mmenu
jna
angularjs-factory
convertapi
babel-core
long-polling
fault
komodoedit
dandelion
statsd
drupal-6
worker-thread
composite-key
cudafy.net
dynamics-sl
minimization
account-kit
mediaelement
background-service
migradoc
xcb
android-fonts
heidisql
google-web-starter-kit
qpid
angstrom-linux
pagedlist
packagist
dlna
photobucket
r-tree
content-length
microbenchmark
service-accounts
method-parameters
apache-commons-fileupload
unity3d-gui
modalpopup
titanium-modules
markers
starcluster
mysql-error-1062
apc
coverflow
tws
sqlperformance
smtp-auth
getmessage
uiviewanimation-curve
whoosh
subgurim-maps
oncheckedchanged
wise
routedevent
asp.net-profiles
ncqrs
mtj
aquaticprime
thread-local-storage
document-conversion

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