Out-of-order writes for Double-checked locking

前端 未结 4 1471
予麋鹿
予麋鹿 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条回答
  •  孤城傲影
    2021-02-06 16:43

    The code in question is here:

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

    Now the problem with this cannot be understood as long as you keep thinking that the code executes in the order it is written. Even if it does, there is the issue of cache synchronization across multiple processors (or cores) in a Symmetrical Multiprocessing architecture, which is the mainstream today.

    Thread1 could for example publish the instance reference to the main memory, but fail to publish any other data inside the Singleton object that was created. Thread2 will observe the object in an inconsistent state.

    As long as Thread2 doesn't enter the synchronized block, the cache synchronization doesn't have to happen, so Thread2 can go on indefinitely without ever observing the Singleton in a consistent state.

提交回复
热议问题