单例模式-DCL

铁子们有段时间没有更新了,最近忙着准备面试,准备过程中发现自己还需要积累的实在是太多太多,每每学到新东西的感觉真是美妙而又动力十足啊,继续伸直腰杆、努力前进。

单例模式-DCL

双重检查判断,使用volatile关键字禁止指令重排,在多线程情况下创建安全的单例对象,直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Instance {

/**
* volatile 禁止指令重排,按照代码执行顺序先赋值后创建对象
*/
private volatile static Instance instance;

private String instName;

private Instance() {
instName = "DCL";
}

public static Instance getInstance() {
if (instance == null) {
synchronized (Instance.class) {
if (instance == null) {
instance = new Instance();
}
}
}
return instance;
}
}

单例模式-内部类

使用内部类构造单例对象,JVM保证单例

1
2
3
4
5
6
7
8
9
10
public class Instance {

private static class InstanceObj {
private static final Instance INSTANCE = new Instance();
}

public static Instance getInstance() {
return InstanceObj.INSTANCE;
}
}

评论