I have worked on a lot of multi-threading programs and I have a question which I havn't been able to find an answer for.
When before you enter a synchronization block, the local thread memory is updated from the "main memory" and when you leave a synchronization block the local thread memory is flushed back to the main memory keeping everyone happy.
But what *excatly* is flushed and is it implementation dependent. 1) Are all variables in the local thread flushed to main memory (ie all variables all the way up the stack).
2) Are all variables in the local thread memory at the top of the stack flushed?
3) Are only variables used within the synchrinization block in the current stack flushed?
I would love to know, since if 1) is the case, then I could probably remove some synchronized blocks which I have and optimise my code.
The answer to the question lies in the Java memory model.
Scotty But what *excatly* is flushed
The answer is that *whatever* is modified by the local thread is flushed to the main memory. So, the option is 1) i believe (if i understood your question correctly.)
Scottyis it implementation dependent
Java memory model is supposed to be followed by all the JVM implementations. So, it is *not* implementation dependent.
There is a catch in it though. The JMM only guarantees that the state of the objects will be consistent between two threads between the point a writing thread releases the lock on a monitor and reading thread acquires a lock on the *same* monitor.
So, if you have two threads working on different monitors but sharing the same data, then the data can be different as seen by two threads.
Scotty: interesting, I guess the reloading of accessable fields is deep, so the full object structure of a field would be reloaded??
Well, for the JVM, it is a memory location and the value stored in that memory location. So, it does not really matter whether the memory location is an object or a primitive type. "Whatever" is stored in that location will be the latest -> This is the guarantee.
The point is that threads while processing a set of instructions copy the values stored at different memory locations in their working memory (Unaware of the fact that it is actually an object). JMM guarantees that the local cache is the latest in specific cases.
This sure will give you an impression that it is a deep copy but under the covers it's a simple memory address and its value.