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 if statements and write lines
Java - Tic Tac Toe Computer move
Java: what does the identifier do in the catch sentence?
Why am I getting an input mismatch exception in thread “main”?
Multiple #Path's in JAX-RS
remove row from jtable
How to specify client version with JClouds-Chef?
How to configure environment variables in Tomcat?
Minimize cost of bundling updates (reverse knapsack?)
Do i need to close connection of mongodb?
Checking if defined and has a Value
I have a video gallery try to get videos files from a specific directory i am getting an error parameters cannot be resolved to a variable
rx java observable chaining on only matched observables
More concise solution using regex in java
Gregorian Calendar month of year [duplicate]
Trying to bring the properties/values such as the names or dates of an XML file into java from a directory

Categories

HOME
variables
atom-editor
layout
vmware
bpmn
google-docs
razor
leon
microservices
cakephp-2.5
packages
mouse
portia
handsontable
google-apps-marketplace
google-cloud-spanner
apache-cayenne
uitypeeditor
pc
sms-gateway
visual-composer
lldb
wkwebview
kvc
crosstab
sparse-matrix
applozic
minitab
saas
webkitspeechrecognition
quote
frame
oracle-fusion-middleware
karaf
calibre
hybridauth
mapdb
nssegmentedcontrol
jmonkeyengine
plsql-psp
multilingual
espeak
opshub
graphenedb
fedex
gulp-sourcemaps
nxlog
netcdf4
auto-update
filepicker
dotnetzip
mplayer
elgg
tactic
pg-dump
zendesk-app
flutterwave
smart-table
word-vba-mac
spring-android
radtreelist
file-writing
intrusion-detection
player
storekit
angstrom-linux
master-slave
ford-fulkerson
unity-networking
endeca-workbench
citrus-pay
tableau-online
ibaction
android-imagebutton
javafx-webengine
qcodo
applescript-objc
openexr
expected-exception
undefined-reference
rtmfp
html5-notifications
inbox
excel-2003
batterylevel
buster.js
eventual-consistency
dmoz
broken-links
gdata-api
pysimplesoap
ocx
windows-phone-7.1.1
assembly-loading
transactionscope
fireworks
data-loss
django-tagging
yetanotherforum
appender
calling-convention
floating
html-input
blitz++
wise
castle-monorail
thunderbird-lightning
meego
substrings
audio-capture
libs
uimenucontroller
temporal-database

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