- 饿汉式:在类加载的时候就完成初始化,获取对象速度快,但类加载较慢。
可能引发线程安全问题。
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
- 懒汉式:类加载时不初始化,调用getInstance()方法时才初始化。可能引发线程安全问题。
public class Singleton {
private static Singleton INSTANCE;
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
- 此外,Java 5及以上版本中,可以使用双重检查锁定(Double-Checked Locking)来安全地实现单例模式,该方法能在JVM中保证线程安全。使用volatile关键字修饰了变量,避免了可见性问题。(详见我之后会写的volatile关键字源码解读…)
public class Singleton {
private static volatile Singleton INSTANCE;
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}