Search code examples
javasynchronizationmonitorsynchronizedjava-memory-model

Java happend-before in synchronized block


I need some help understanding the Java memory model.The following is a gerneric example to grasp the basic concept:

Image I have an object instance called Shared and two threads A and B. Furthermore there is some kind of Queue with a synchronized put and take.

Thread A modifies the Shared-instance before and in the put method.

Question 1: All changes from A are visible when B gets the Shared-object instance through the synchronized take-method?

Question 2: The memory cache is flushed (all changes on Shared are visible) as soon as A leaves the synchronized put-method. What exaclty happens if wait() is called in the put-method by A? Will B also see the changes done to Shared even though A hasn't yet exited the synchronized-method? Is the cache also flushed when calling wait()?


Solution

  • Answer 1: Yes. Because both take() and put() are synchronized. So before B could execute take(), A should have left the synchronized block and leaving the synchronized block means flushing memory cache(memory fence/barrier).

    Answer 2: Yes. Because when wait() is called, the thread has to surrender the lock, which will again cause memory flushing.

    EDIT: I think what you are after is that whether cache-write-to-memory happens on exit of synchronized block or release of lock. The answer is cache-write-to-memory happens on release of lock.