1、基于volatile
public class SafeDoubleCheckedLocking {
private volatile static SafeDoubleCheckedLocking instance;
public static SafeDoubleCheckedLocking getInstance() {
if (instance == null) {
synchronized (SafeDoubleCheckedLocking.class) {
if (instance == null) {
instance = new SafeDoubleCheckedLocking();
}
}
}
return instance;
}
}
2、基于类初始化
public class InstanceFactory {
private static class InstanceHolder {
public static InstanceFactory instance = new InstanceFactory();
}
public static InstanceFactory getInstance() {
return InstanceHolder.instance;
}
}