双重校验锁实现对象单例(线程安全)
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
@Override
protected Singleton clone(){
return uniqueInstance;
}
}
内部类
public class LazyInnerClassSingleton {
private LazyInnerClassSingleton(){
if(LazyHolder.LAZY!=null){
throw new RuntimeException("不容许创建多个实例");
}
}
public static final LazyInnerClassSingleton getInstance(){
return LazyHolder.LAZY;
}
private static class LazyHolder{
private static final LazyInnerClassSingleton LAZY = new LazyInnerClassSingleton();
}
private Object readResolve(){
return LazyHolder.LAZY;
}
}