Blogger

Delete comment from: Javarevisited

Anonymous said...

As others have pointed out this blog is misleading. Volatile in your example has nothing to do with ensuring the field is non-null (this guarantee would actually cause a problem in the original Java memory model - see link below).

As I found this blog by googling "java volatile" people are probably reading it and getting incorrect information.

The example you provided requires a volatile because the reading of a volatile (assuming later Java memory model) guarantees that a previous write to the volatile has completed, and this in turn guarantees the object was constructed completely because of "as-if-serial" preservation and its rules regarding volatile. Without a volatile, _instance could be written to in a thread and "leaked" out of its local memory into another thread before the object is constructed fully, because "as-if-serial" rules in that case would allow reordering within the thread as long as that thread isn't affected.

You should read this and re-write the blog (or just link to this page which explains it anyway):
http://www.ibm.com/developerworks/library/j-jtp03304/

It also explains why you probably shouldn't bother with double checked locking, something missing here.

Sep 27, 2012, 5:57:06 AM


Posted to How Volatile in Java works? Example of volatile keyword in Java

Google apps
Main menu