How to write a thread-safe Singleton?

[Method 1]




public class MySingleton
{
private static MySingleton instance = new MySingleton();
private MySingleton()
{
// construct the singleton instance
}

public static MySingleton getInstance()
{
return instance;
}
}

[Method 2]
public class MySingleton {
private static MySingleton instance = null ;
private MySingleton() {
// construct the singleton instance
}
public synchronized static MySingleton getInstance() {
if (instance == null ) {
instance = new MySingleton();
}
return instance;
}
}

[Method 3]
public class MySingleton {
private static boolean initialized = false ;
private static Object lock = new Object();
private static MySingleton instance = null ;
private MySingleton() {
// construct the singleton instance
}
public static MySingleton getInstance() {
if (!initialized) {
synchronized (lock) {
if (instance == null ) {
instance = new MySingleton();
initialized = true ;
}
}
}
return instance;
}
}

你可能感兴趣的:(How to write a thread-safe Singleton?)