双重校验锁 DCL
public class Singleton {
private volatile static Singleton mSingleton;
public static Singleton getInstance(){
if (mSingleton==null){
synchronized (Singleton.class){//类锁与静态锁功能一致
if (mSingleton==null){
mSingleton=new Singleton();
}
}
}
return mSingleton;
}
}
volatile的两层含义:
- 可见性。可见性是指在一个线程中对该变量的修改会马上由工作内存(Work Memory)写回主内存(Main Memory),所以会马上反应在其线程的读取操作中。
- 禁止指令重排优化,但是这个语义知道jdk1.5以后才能正确工作。
https://www.cnblogs.com/takumicx/p/9302398.html
静态内部类方式实现单例模式
public class Singleton {
public Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
/**
* 防止反序列化获取更多个对象的漏洞
* @return
* @throws ObjectStreamException
*/
private Singleton readResolve()throws ObjectStreamException {
return SingletonHolder.INSTANCE;
}
}
枚举方式实现单例模式
public enum Singleton {
INSTANCE;
private SingletonTest mSingleton;
Singleton() {
}
public SingletonTest getInstance() {
if (mSingleton == null) {
mSingleton = new SingletonTest();
}
return mSingleton;
}
public class SingletonTest {
}
}