1

Check out this java code snippet:

 Lock l = ReentrantLock();
 l.lock();
 try {
     counter++;
 } finally {
     l.unlock();
 }

This code guarantees that only one thread will execute the code in the try block in a particular time.

My question is: how the lock/unlock mechanism guarantees memory visibility between the threads? (what is the mechanism that will make sure that the counter result will be flushed into the main memory by Thread X, and will be loaded from the main memory by Thread Y that will come afterward?)

0

1 Answer 1

1

http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5

17.4.5. Happens-before Order

Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second.

...

It follows from the above definitions that:

An unlock on a monitor happens-before every subsequent lock on that monitor.

...

In a happens-before consistent set of actions, each read sees a write that it is allowed to see by the happens-before ordering.

The seeing is implied to be seeing from a different thread.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reference, it explains there is happens-before relation between unlock and the next lock (which is reasonable), but it still does not explain why the data between the original lock to the unlock is the one to be synced to the next thread..
The reason why Thread B, may see a different value than Thread A is because of instruction reordering, among other things. This page explains why a Happens-Before relationship ensures memory consistency: docs.oracle.com/javase/tutorial/essential/concurrency/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.