Although Java Memory Model is documented well, I was still wondering which assembler instructions are used to ensure “happens-before” guarantees at multi-core CPU level.
I managed to get some free time and play with java at low level and tested three synchronization techniques. I also found a good documentation explaining Synchronized Memory Access details.
According to Microsoft’s x86 Architecture following actions happen for lock instructions.
- Before issuing the instruction, the CPU will flush all pending memory operations to ensure coherency. All data pre-fetches are abandoned.
- While issuing the instruction, the CPU will have exclusive access to the bus. This ensures the atomicity of the load/modify/store operation.
Synchronized
That technique uses synchronized keyword to lock variables properly. As it synchs whole method block, therefore there are two lock cmpxchg instructions in the generated assembly code.
Volatile
Below code piece uses volatile keyword to set the counter value.Volatile keyword causes inserting a lock instruction to ensure happens-before guarantees and flushes pending changes to make sure these changes are visible.
Atomic
Below code shows a simple AtomicInteger being used a counter.When above code is executed with -XX:+UnlockDiagnosticVMOptions -XX:CompileCommand=print,Counter.inc, similar assembly instructions are seen in the assembly dump log.
Brilliant overview. Thank you very much for the references as well!
ReplyDeleteHi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java EE Online Training from India. or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.
ReplyDeleteYou know after a hard day I decided to have fun and play games of chance I climbed a bunch of sites and only on this I understood what was happening prosperous gambling help now I sit and spend all the time on this site
ReplyDelete