Out-of-order writes for Double-checked locking

前端 未结 4 1473
予麋鹿
予麋鹿 2021-02-06 15:44

In the examples mentioned for Out-of-order writes for double-checked locking scenarios (ref: IBM article & Wikipedia Article)

I could not understand the simple reaso

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 16:33

    Thread 2 checks to see if the instance is null when Thread 1 is at //3 .

    public static Singleton getInstance()
    {
    if (instance == null)
    {
    synchronized(Singleton.class) {  //1
      if (instance == null)          //2
        instance = new Singleton();  //3
      }
    }
     return instance;//4
    }
    

    At this point the memory for instance has been allocated from the heap and the pointer to it is stored in the instance reference, so the "if statement" executed by Thread 2 returns "false". Note that because instance is not null when Thread2 checks it, thread 2 does not enter the synchronized block and instead returns a reference to a " fully constructed, but partially initialized, Singleton object."

提交回复
热议问题