Reading Java VM specification gives interesting insights of the synchronized keyword usage.

VM Specification: Threads and Locks

For good fun, read chapter 8.11. I.e.

… Because there is no synchronization, it is at the option of the implementation whether or not to store the assigned values back to main memory! …

This means that if synchronization is not used properly. Then code is broken. Which tends to mean that it works in developer’s own limited ”test cases”, while failing in real life occasionally with mysterious results.

When dealing with synchronization, it must be noted that these ”main memory” and ”working memory” concepts for threads are very likely to become issue when SMP systems are used. While on the other hand, it is very likely that developer’s are themselves testing only (a) without server JVM, (b) under debugger, (c) using single CPU machine, (d) using only single OS.

Luckily chapter 8.9 states:

.. Locking any lock conceptually flushes all variables from a thread’s working memory, and unlocking any lock forces the writing out to main memory of all variables that the thread has assigned. …

This means that synchronized flushes not only changes occuring during synchronized block, but also pending changes which potentially exist in thread’s local working memory. However, beware the beholder, this means also that using synchronized is expensive since it requires accessing shared memory (i.e. reading/writing data to/from main memory).

/ java

Vastaa

Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *

This site uses Akismet to reduce spam. Learn how your comment data is processed.