Trouble understanding the semantics of volatile in Java
Posted
by
HungryTux
on Stack Overflow
See other posts from Stack Overflow
or by HungryTux
Published on 2012-09-22T02:55:20Z
Indexed on
2012/09/22
3:37 UTC
Read the original article
Hit count: 124
I've been reading up about the use of volatile
variables in Java. I understand that they ensure instant visibility of their latest updates to all the threads running in the system on different cores/processors. However no atomicity of the operations that caused these updates is ensured. I see the following literature being used frequently
A write to a volatile field happens-before every read of that same field .
This is where I am a little confused. Here's a snippet of code which should help me better explain my query.
volatile int x = 0;
volatile int y = 0;
Thread-0: | Thread-1:
|
if (x==1) { | if (y==1) {
return false; | return false;
} else { | } else {
y=1; | x=1;
return true; | return true;
} | }
Since x & y are both volatile
, we have the following happens-before edges
- between the write of y in Thread-0 and read of y in Thread-1
- between the write of x in Thread-1 and read of x in Thread-0
Does this imply that, at any point of time, only one of the threads can be in its 'else' block(since a write would happen before the read)?
It may well be possible that Thread-0 starts, loads x, finds it value as 0 and right before it is about to write y in the else-block, there's a context switch to Thread-1 which loads y finds it value as 0 and thus enters the else-block too. Does volatile
guard against such context switches (seems very unlikely)?
© Stack Overflow or respective owner