Happen to Relationship in Java Memory Model
I have a question about Java Memory Model.
In the following script: initial: a = 0; b = 0;
T1:
a = 1;
l.lock();
b = 1;
l.unlock();
T2:
l.lock();
read b;
l.unlock();
read a;
Can I say that the value b
read T2
is equal 1
, then the value a
read T2
should be 1
?
As far as I understand, unlock
c T1
performs a reset both to the value a
and b
to main memory, while lock
c T2
provides both read a
and read b
can get the last value.
I'm right?
Edit: I just pointed out that they are locked on the same lock.
source to share
Can I tell if the b value read by T2 is 1, then the value of T2 read should be 1?
Yes. This is guaranteed. An activity can move to a synchronized block, but not from it. See Jeremy Manson's blog post Roach Motels and the Java Memory Model .
This means that although it read a
can move up to unlock
(and higher read b
due to command reordering), it can never move up above an instruction lock
T2
.
The same reasoning applies for a = 1
: it can move down into a synchronized block (and below b = 1
due to command reordering), but does not pass the instruction unlock
.
However, if we change the instructions in this way, they will both be locked by a lock, which means that if it T2
reads 1
from b
, then T1
already wrote a 1
before b
.
source to share
I find useful information from http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html .
How does sync work? section:
'Synchronization ensures that writing in memory by a stream before or during a synchronized block becomes visible in a predictable manner to other threads that are synchronized on the same monitor. After exiting the synchronized block, we exit the monitor, which causes the cache to be flushed to main memory so that the records created by this thread can be seen by other threads. Before we can enter a synchronized block, we have a monitor that has the effect of invalidating the local processor cache, so that the variables will be reloaded from main memory. Then we can see all the entries made visible by the previous version. '
'This means that any memory operations that were visible on a thread before exiting a synchronized block are visible to any thread after it enters a synchronized block protected by the same monitor, since all memory operations occur before release , and the release occurs prior to acquisition.
source to share