How to write a thread-safe Singleton?

来源:互联网 发布:电话录音软件 iphone 编辑:程序博客网 时间:2024/05/21 09:26
[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;
}
}
原创粉丝点击