面经读后感-双重检查笔记

感觉看面经是个提高自己的好方式……
代码:

1
2
3
4
5
6
7
8
9
10
public static Singleton instance;
public static Singleton getInstance(){
if (instance == null){ //1
synchronized(Singleton.class) { //2
if (instance == null) //3
instance = new Singleton(); //4
}
}
return instance;
}

问题:
双线程同时执行getInstance()方法,线程1执行到第4步,而实例化对象在JVM中分为两步:分配内存+创建对象
如果在创建对象之前,线程2执行到第1步,发现内存已经分配了,返回这个引用就会出现问题。
解决:

1
public volatile static Singleton instance;

加上volatile就可以保证语句的有序性(1.4之前不行),强制实例化对象先创建 再分配内存,其他线程执行到1时,如果instance不是null则对象必然创建完成。

面经读后感-双重检查笔记

http://blog.mothership.top/posts/d3b34d98.html

作者

Mother Ship

发布于

2018-11-15

更新于

2023-02-13

许可协议

评论