为什么Java中不能使用Double Checked Locking模式

2020-10-18 教育 72阅读
如果在constructor中对final字段赋值,JVM保证先把这些值提交到内存,然后才会更新内存中的对象引用。
换句话说,另外一个能看到这个对象的线程不能看到没有初始化过的final字段。
在Factory类的所有字段都是final字段这种情况下,我们实际上没有必要申明factory实例为volatile。
In Java 5, a change was made to the definition of final fields. Where the values of these fields are set in the constructor, the JVM ensures that these values are committed to main memorybefore the object reference itself. In other words, another thread that can "see" the objectcannot ever see uninitialised values of its final fields. In that case, we wouldn't actually need to declare the instance reference as volatile.
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com