单例模式
- 饿汉式
public class SingletonTest {
private SingletonTest test2 = new SingletonTest();
/**
* 饿汉式:如果系统没有使用,会造成资源浪费
* 如果初始化中,执行代码多,会使启动慢
*/
public SingletonTest getInst() {
return test2;
}
- 懒汉式
public class SingletonTest {
private SingletonTest test = null;
/**
* 懒汉式1 多线程时有并发问题
*/
public SingletonTest getInstance() {
if (test == null) {
test = new SingletonTest();
}
return test;
}
/**
* 懒汉式2 有性能开销 不推荐
*/
public synchronized SingletonTest getInstance2() {
if (test == null) {
test = new SingletonTest();
}
return test;
}
- 双重检测+同步锁
双重校验锁模式不加volatile的影响会线程不安全分析
对象的创建分几步,其中有
1 分配内存空间
2 初始化对象
3 设置instance指向内存地址
如果jvm发生指令重排序,顺序变成1 3 2,那么另一个线程可能会得到null
public class SingletonTest {
// 必须加上 volatile
private volatile SingletonTest test = null;
private SingletonTest() {
}
/**
* 双重检测+同步锁
*/
public SingletonTest getInstance3() {
if (test == null) {
synchronized (SingletonTest.class) {
if (test == null) {
test = new SingletonTest();
}
}}
return test;
}
}
- 枚举
public class EnumTest {
private EnumTest(){}
public static EnumTest getInstance(){
return Singleton.INSTANCE.getInstance();
}
private enum Singleton{
/**/
INSTANCE ;
private EnumTest enumTest ;
// JVM 来保证只会调用一次
Singleton(){
enumTest = new EnumTest();
}
public EnumTest getInstance(){
return enumTest;
}
}
}