This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I've been looking for an answer to my question for quite some time. No luck though...
Let's say one thread waits for changes of variable int "state".
First it enters synchronized block synchronized(guard) modifies "state" and releases lock of the guard object via guard.wait().
Now second thread modifies variable "state" also in synchronized block notifies first thread and leaves the block.
First thread resumes from wait() and checks the value of "state"
My question is. Does the "state" variable is being flushed to original location in memory from CPU registers
when wait() is called? In other words does thread 2 sees changes made by thread 1 before calling wait()?
I know that variables are "flushed" when synchronized block is reached and leaved but I'm not sure
about that wait() call. In theory wait() releases lock so all variables that has been modified and are in registers
should be flushed...
To clarify I'm talking about non-volatile variables.
Your thought is correct. The memory is guaranteed to be flushed when a monitor is released, and wait does cause the monitor to be released. Another way to think of it is that when thread1 calls notify it must be in the synchronized block. So it must leave the synchronized block before thread2 can wake up and read the state variable. And when thread1 leaves the synchronized block, the memory will be flushed. I'm not sure of the exact semantics as to if it gets flushed when wait is called or when thread1 leaves the synchronized block or both, but the end result is that thread2 will see the updated value written by thread 1.