Why is volatile used in double checked locking

后端 未结 7 816
太阳男子
太阳男子 2020-11-22 05:01

From Head First design patterns book, the singleton pattern with double checked locking has been implemented as below:

public class Singleton {
            


        
7条回答
  •  礼貌的吻别
    2020-11-22 05:29

    A good resource for understanding why volatile is needed comes from the JCIP book. Wikipedia has a decent explanation of that material as well.

    The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. This results in Thread B failing because it is using a partially constructed version of instance.

提交回复
热议问题