刚刚来新公司,发现项目中大量的单例使用的双重检查锁方式的单例,但是很奇怪并没有加volatile修饰词。
认真复习了一下volatile参数,发现这个确实有必要加的。但是究竟不加volatile会不会出现问题呢?
按照已知的理解,new一个新对象时,出现一下原子操作:
- 分配内存空间。
- 初始化对象。
- 将内存空间的地址赋值给对应的引用。
如果不使用volatile参数的话,可能会出现1-3-2的执行顺序,这样就会导致在判断instance == null时,instance不为空,直接返回了instance,但实际上这个instance仍然为null的。
使用了volatile这个参数,会禁止重排序,是以上过程按照1-2-3的顺序执行。
然后我使用CountDownLatch模拟了一个高并发,测试是否有instance == null为null的情况出现。
很遗憾,在mac上线程加到2000个尝试同时唤醒(实际上并不会这么多,因为cpu有限),安卓尝试300个线程同时唤醒,反复好多次,仍然没有出现为null的情况。
和旁边技术不错的同事聊了聊,认为,这种情况,需要在配置高的服务器(cpu多核)并且大量并发时可能出现,安卓机或者我这个低配mac上,出现概率较小。
算是一次失败的测试吧。记录一下。
参考文章:知乎讨论
附上测试类:
public class Singleton {
//故意没有加 volatile参数
private static Singleton instance;
private Singleton() {
}
//双重加锁单例模式
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
public static void main(String[] args) {
init();
}
/**
* 线程数量
*/
public static final int THREAD_NUM = 1000;
/**
* 开始时间
*/
private static long startTime = 0L;
private static volatile int num = 0;
public static void init() {
try {
startTime = System.currentTimeMillis();
System.out.println("CountDownLatch started at: " + startTime);
// 初始化计数器为1
CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i = 0; i < THREAD_NUM; i++) {
new Thread(new Run(countDownLatch)).start();
}
// 启动多个线程
countDownLatch.countDown();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
/**
* 线程类
*/
private static class Run implements Runnable {
private final CountDownLatch startLatch;
public Run(CountDownLatch startLatch) {
this.startLatch = startLatch;
}
@Override
public void run() {
try {
// 线程等待
startLatch.await();
// 执行操作
Singleton instance = getInstance();
if (instance == null) {
System.out.print("Thread.currentThread() =" + Thread.currentThread().getId() + (instance == null ? "instance = null" : " " + "\n"));
}
// num = num + 1;
// System.out.print("num = " + num + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}