Topic
  • 3 replies
  • Latest Post - ‏2007-06-29T00:57:12Z by SystemAdmin
SystemAdmin
SystemAdmin
757 Posts

Pinned topic Double checked locking in 1.5 with volatile?

‏2007-06-22T19:54:25Z |
Does double checked locking work with volatile in Java 1.5 for singletons?

Will this code work?

public class Singleton
{
static volatile Singleton instance = null;

public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
// ensure that Object is fully constructed before assigning
// to instance
Singleton temp = new Singleton();
instance = temp;
}
}
}
return instance;
}
}
Updated on 2007-06-29T00:57:12Z at 2007-06-29T00:57:12Z by SystemAdmin
  • SystemAdmin
    SystemAdmin
    757 Posts

    Re: Double checked locking in 1.5 with volatile?

    ‏2007-06-26T14:25:23Z  
    No, it won't help. The volitile keyword should actually exacerbate the problem with double-checked locking.

    FTA - "Volatile variables share the visibility features of synchronized, but none of the atomicity features."

    By lack of atomicity and removing compiler optimizations, the visibility of change should be increased.

    Unless I'm completely wrong ;-)

    Paul Davis
    willcode4beer.com
  • SystemAdmin
    SystemAdmin
    757 Posts

    Re: Double checked locking in 1.5 with volatile?

    ‏2007-06-26T14:33:59Z  
    No, it won't help. The volitile keyword should actually exacerbate the problem with double-checked locking.

    FTA - "Volatile variables share the visibility features of synchronized, but none of the atomicity features."

    By lack of atomicity and removing compiler optimizations, the visibility of change should be increased.

    Unless I'm completely wrong ;-)

    Paul Davis
    willcode4beer.com
    I believe you are completely wrong. The old problem with double-checked locking was a problem of visibility on the first check.
  • SystemAdmin
    SystemAdmin
    757 Posts

    Re: Double checked locking in 1.5 with volatile?

    ‏2007-06-29T00:57:12Z  
    I believe you are completely wrong. The old problem with double-checked locking was a problem of visibility on the first check.
    I've been thinking about this a bit lately, and stumbled upon this old (2002) article, here in developerWorks about this specific issue.

    http://www.ibm.com/developerworks/java/library/j-dcl.html

    However, I've found much more information that suggests that using volatile for double checked locking is okay since Java 1.5.

    So, I am wrong, the 2002 article would have me right on a technicality but, I would still be wrong factually.

    Thanks
    Paul Davis
    willcode4beer.com