CodeEggDailyInterview icon indicating copy to clipboard operation
CodeEggDailyInterview copied to clipboard

单例的DCL方式下,那个单例的私有变量要不要加volatile关键字

Open kukyxs opened this issue 5 years ago • 1 comments

kukyxs avatar Dec 22 '19 23:12 kukyxs

需要,new某个对象,可以分解为:

1 memory=allocate();// 分配内存 相当于c的malloc 2 ctorInstanc(memory) //初始化对象 3 instance=memory //设置instance指向刚分配的地址

在编译器运行时,可能会出现重排序 从1-2-3 排序为1-3-2

如此在多线程下就会出现问题例如现在有2个线程A,B 线程A在执行第5行代码时,B线程进来,而此时A执行了 1和3,没有执行2, 此时B线程判断instance不为null 直接返回一个未初始化的对象,就会出现问题 而用了volatile,上面的重排序就会在多线程环境中禁止,不会出现上述问题。

kukyxs avatar Dec 23 '19 13:12 kukyxs