如何安全发布对象?

安全发布对象详解~

  • 在静态初始化函数中初始化一个对象引用
  • 将对象的引用保存到volatile类型域或者AtomicReference对象中
  • 将对象的引用保存到某个正确构造对象的final类型域中
  • 将对象的引用保存到一个由锁保护的域中

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 懒汉模式 -》 双重同步锁单例模式
* 单例实例在第一次使用时进行创建
*/
@ThreadSafe
public class LazySingleton {

// 私有构造函数
private LazySingleton() {}

// 1、memory = allocate() 分配对象的内存空间
// 2、ctorInstance() 初始化对象
// 3、instance = memory 设置instance指向刚分配的内存

// 单例对象 volatile + 双重检测机制 -> 禁止指令重排
private volatile static LazySingleton instance = null;

// 静态的工厂方法
public static LazySingleton getInstance() {
if (instance == null) { // 双重检测机制
synchronized (LazySingleton.class) { // 同步锁
if (instance == null) {
instance = new LazySingleton();
}
}
}
return instance;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 饿汉模式
* 单例实例在类装载时进行创建
*/
@ThreadSafe
public class HungrySingleton {

// 私有构造函数
private HungrySingleton() {}

// 单例对象
private static HungrySingleton instance = new HungrySingleton();

/*
private static SingletonExample6 instance = null;

static {
instance = new SingletonExample6();
}*/

// 静态的工厂方法
public static HungrySingleton getInstance() {
return instance;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 枚举模式:最安全
*/
@ThreadSafe
@Recommend
public class EnumSingleton {

// 私有构造函数
private EnumSingleton() {}

public static EnumSingleton getInstance() {
return Singleton.INSTANCE.getInstance();
}

private enum Singleton {
INSTANCE;

private EnumSingleton singleton;

// JVM保证这个方法绝对只调用一次
Singleton() {
singleton = new EnumSingleton();
}

public EnumSingleton getInstance() {
return singleton;
}
}
}