Singleton design pattern broken?

admin

Administrator
Staff member
<blockquote>
<strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java">Efficient way to implement singleton pattern in Java</a>
</blockquote>



I would have thought that class below is a thread safe singleton but reading <a href="http://taskinoor.wordpress.com/2011/04/18/singleton_multithreaded/" rel="nofollow noreferrer">http://taskinoor.wordpress.com/2011/04/18/singleton_multithreaded/</a> it seems it is not.

Code:
public class ThreadSafeSingleton {

    private static ThreadSafeSingleton ref;

    private ThreadSafeSingleton(){

    }

    public ThreadSafeSingleton getSingletonObject(){

        if(ref == null){
            ref = new ThreadSafeSingleton();
        }   
        return ref;

    }
}

According to the article the only truly thread safe singleton is -

Code:
public class ThreadSafeSingleton {

    private static ThreadSafeSingleton ref = new ThreadSafeSingleton();

    private ThreadSafeSingleton(){

    }

    public ThreadSafeSingleton getSingletonObject(){
        return ref;

    }
}

Is this correct ?