Sunday, February 22, 2009

Volatility

In the last few months, I've found myself writing a lot more multi-threaded programs than I usually do. This made me reflect upon some of the constructs Java provides for multi-threading. Two such constructs are the volatile and synchronized keywords. In my years working with a wide range of developers, I've found that most know (at least at a cursory level) what synchronized means, but very few know what volatile means or when it should be used.


The semantics of the volatile keyword are similar to those of the synchronized keyword, but they're not equivalent. When one thinks of multi-threaded programs, they have 3 primary properties: visibility - the ability of one thread to see the work of another thread, atomicity - defining sets of indivisible actions, and ordering - enforcing that some operations in one thread happen before others in another. Using synchronized, a developer can enforce all three properties. When one uses volatile, however, one cannot enforce atomicity.


Why would one want to use volatile over synchronized since it seems to be a less powerful construct? Well, for one thing, it incurs slightly less overhead than obtaining locks with synchronized. Additionally, volatile can be used on primitives and null values (you can't directly synchronize on a primitive). One common use case is for a flag value that is updated by one thread but read by another. Declaring it volatile ensures that the other thread is reading the current value and not its own cached copy.


Java is an interesting programming language for many reasons, not the least of which is the way it insulates the developer from so many concerns of the low-level machine. The difference between volatile and synchronized, however, illustrates that, despite this abstraction, developers are obligated to understand the inner workings of the JVM if they are to write correct and efficient code.

1 comment:

  1. First post - congrats! Simply and nicely done! PhR

    ReplyDelete