3 ms·
Yay memory semantics! A classic case where this sort of problem bit Java in the ass: the "double-checked locking pattern" for initializing Singletons. http://w
by lincolnq 14y ago
Yay memory semantics!
A classic case where this sort of problem bit Java in the ass: the "double-checked locking pattern" for initializing Singletons. http://www.ibm.com/developerworks/java/library/j-dcl/index.html http://www.ibm.com/developerworks/java/library/j-dcl/index.h...
I'm not sure if this was ever fixed / improved enough to allow the programmer to make this work.
- mjb 14y ago> A classic case where this sort of problem bit Java in the ass I'm not sure what you mean by "bit Java in the ass". Perhaps pre-Java 5 (or pre JSR133 more accurately) the reason this was broken was poorly defined. In modern Java it's quite clear that the Java memory model implies that the double-checked-locking idiom doesn't work. See http://jeremymanson.blogspot.com/2008/05/double-checked-locking.html http://jeremymanson.blogspot.com/2008/05/double-checked-lock... and http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLo... for more information. Making the variable volatile fixes it. > 'm not sure if this was ever fixed / improved enough to allow the programmer to make this work. I don't know what the value of "making it work" would be. Uncontended access to a volatile is very cheap (see http://brooker.co.za/blog/2012/09/10/volatile.html http://brooker.co.za/blog/2012/09/10/volatile.html for some timings on x86), and in very performance sensitive code you'll probably not want to do lazy allocation anyways. The well defined and well-understood memory model in modern Java is one of the real strengths of the language (and platform).
- trhtrsh 14y agoThe "fix" is to define an enum with one member named INSTANCE, if you need a Singleton. -- Effective Java, 2/ed, bu Josh Bloch
- oconnor0 14y agoWhich only works if you need something that doesn't extend existing classes but only interfaces.