How to solve the "Double-Checked Locking is Broken" Declaration in Java?

Viewed 25661

I want to implement lazy initialization for multithreading in Java.
I have some code of the sort:

class Foo {
    private Helper helper = null;
    public Helper getHelper() {
        if (helper == null) {
            Helper h;
            synchronized(this) {
                h = helper;
                if (h == null) 
                    synchronized (this) {
                        h = new Helper();
                    } // release inner synchronization lock
                helper = h;
            } 
        }    
        return helper;
    }
    // other functions and members...
}

And I'm getting the the "Double-Checked Locking is Broken" declaration.
How can I solve this?

9 Answers

If I'm not mistaken, there is also another solution if we do not want to use the volatile keyword

for example by taking the previous example

    class Foo {
        private Helper helper = null;
        public Helper getHelper() {
            if (helper == null) {
                synchronized(this) {
                    if (helper == null)
                        Helper newHelper = new Helper();
                        helper = newHelper;
                }
            }
            return helper;
        }
     }

the test is always on the helper variable but the construction of the object is done just before with the newHelper, it avoids to have a partially constructed object

Related