Thread safety in Singleton

Posted by Robert on Stack Overflow See other posts from Stack Overflow or by Robert
Published on 2010-05-26T11:04:55Z Indexed on 2010/05/26 11:11 UTC
Read the original article Hit count: 401

Filed under:
|
|

I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:

class Singleton{
    private static Singleton instance;

    private Singleton(){}

    public static synchronized Singleton getInstance(){
        if(instance == null) instance = new Singleton();
        return instance;
    }
}

Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading