If you still haven't brushed up on the issues of Java concurrency, this 10 part series will take you through most of its issues drawing analogies from more mundane topics. Among the topics you will find 'The Law of the Leaked Memo', 'The Law of the Blind Spot','The Law of the Distracted Spearfisherman' and 'The Law of the Corrupt Politician' among other titles loaded with the technical details behind Java concurrency. Number 8 in this 10 part series -- entitled 'The Law of Cretan Driving' -- goes into the details enforced by the virtual machine and how it influences concurrency.
The Java Virtual Machine Specification was written with a large range of hardware architectures in mind. It is thus not surprising that it contains several rules that would usually not be enforced. However, if you break the rules, especially in concurrency, you might be surprised by a rather large fine one day. What makes this tricky is that even though your code might execute correctly on all the JVM implementations to date, you might still contain concurrency bugs that only show up on other architectures. As Java Specialists, we should have read the Java Virtual Machine Specification and the Java Memory Model JSR 133 at least once. The Java Language Specification is also recommended reading for Java experts. (Now you have enough reading material to cure your insomnia...) For example, here is an extract from the Java Memory Model: "VM implementers are encouraged to avoid splitting their 64-bit values where possible. Programmers are encouraged to declare shared 64-bit values as volatile or synchronize their programs correctly to avoid this." That is like saying: "Traffic police are encouraged to allow people to not wear seat belts, where possible. Drivers are encouraged to wear seat belts to avoid fines." The only way for the driver to be safe from fines would thus be to wear a seat belt all the time. However, the probability of a fine would still be so low that most of the time you would get away with breaking the law. The Memory Model extract implies the following. Let's take the following code: public class LongFields { private long value; public void set(long v) { value = v; } public long get() { return value; } } If we call this method set() with values 0x12345678ABCD0000L and 0x1111111111111111L from two different threads, the value field could end up as 0x11111111ABCD0000L or 0x1234567811111111L. If this happens in your code, it is a bug in your code, not in the JVM. I have not seen it happen in real life, since none of the JVMs that I used split the 64 bit values, to my knowledge.
Read the complete post on 'The Law of Cretan Driving': http://www.javaspecialists.eu/archive/Issue156.html The entire series titles can be found here: http://www.javaspecialists.eu/archive/newsletters.jsp?category=Concurrency