线程安全的懒汉单例模式
在Java中,单例模式分为饿汉式和懒汉式。默认情况下,懒汉式是线程不安全的,懒汉式代码如下:
class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance () throws InterruptedException {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
让懒汉式变成线程安全也非常简单,只需使用同步方法即可.
public static synchronized Singleton getInstance () {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
但上述代码的性能不是太高,还有可修改的地方。
public static Singleton getInstance ()
{
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}