public class SingletonOne {
// volatile 禁止指令重排序优化
private static volatile SingletonOne instance = null;
private SingletonOne() {
}
// synchronized 修饰的同步方法比一般的方法要慢很多。所以此处使用双重校验锁。
public static SingletonOne getInstance() {
if (null == instance) {
synchronized(SingletonOne.class) {
if (null == instance) {
instance = new SingletonOne();
}
}
}
return instance;
}}
second 饿汉式 不推荐
public class SingletonTwo {
private static SingletonTwo instance = new SingletonTwo();
private SingletonTwo() {
}
public static SingletonTwo getInstance() {
return instance;
}}
third 静态内部类加载
public class SingletonThree {
private SingletonThree() {
}
private static class SingletonHolder {
public static SingletonThree instance = new SingletonThree();
}
public static SingletonThree getInstance() {
return SingletonHolder.instance;
}}