Wednesday, 15 January 2014

Happen before relationship in Java Memory Model -



Happen before relationship in Java Memory Model -

i have question java memory model.

in next scenario: initial: a = 0; b = 0;

t1: = 1; l.lock(); b = 1; l.unlock(); t2: l.lock(); read b; l.unlock(); read a;

can if value of b read t2 1, value of a read t2 must 1?

to understanding, unlock in t1 flushes both value of a , b main memory, , lock in t2 makes sure both read a , read b can latest value.

am right?

edit: specified locked on same lock.

can if value of b read t2 1, value of read t2 must 1?

yes. it's guaranteed. operation can move into synchronized block, not out it. see jeremy mansons blog post roach motels , java memory model.

this means that, while read a can move before unlock, (and above read b due instruction reordering) can never move above lock instruction of t2.

same reasoning applies a = 1: can move downwards synchronized block (and below b = 1 due instruction reordering) not passed unlock instruction.

however, if swap instructions that, both covered lock, means if t2 reads 1 b, t1 have written 1 b.

java java-memory-model

No comments:

Post a Comment