I have been researching the Java Memory Model all day today, in order to understand in detail the problems with the JMM pre-Java 5 and the changes made by JSR-133 implemented in Java 5.
What I cannot seem to find a definitive answer on is the scope of cache invalidation and flushing required on a particular synchronize.
Must all CPU registers and caches be invalidated when entering any synchronized portion of code and all flushed to main RAM when leaving, or is the JVM allowed to only invalidate those variables actually read, and flush only those actually written during the synchronized block of code?
If the former, why is the JMM so pedantic about insisting the that memory barrier only occurs between two threads which synchronize on exactly the same object?
If the latter, is there any good document that explains the details of how this is accomplished? (I would suppose the underlying implementation would have to set a "bypass caches" flag at the CPU level at the start of a synchronized block and clear it at the end, but I could be way off base.)
The synchronized keyword prevents concurrent access to a block of code or object by multiple threads. All the methods of Hashtable are synchronized , so only one thread can execute any of them at a time.
To make this code properly synchronized in Java you need to either make both method static or nonstatic or use java synchronized block instead of java synchronized method. By the way, this is one of the common mistake Java developers make while synchronizing their code.
Synchronization is usually needed when you are sharing data between multiple invocations and there is a possibility that the data would be modified resulting in inconsistency. If the data is read-only then you dont need to synchronize.
Because of the rules involving cache flushing and invalidation, a synchronized block in the Java language is generally more expensive than the critical section facilities offered by many platforms, which are usually implemented with an atomic "test and set bit" machine instruction.
There is very nice tech talk on Java Memory model. If you dislike wideos google 'happens before'
in context of Java Memory Model.
Basically all writes are visible to other threads if there is happens before relationship, Lets assume thaat thread A writes to field X, and thread B reads from it, so happens before is establishend between write and read if:
So I think that the second option is true, how they implemented it, I dont know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With