Hidden Dangers and Optimization of Double Check Locks in Single Case Mode

  Excerpt and summary ------

(1) Double check lock of traditional single case mode

public class Singleton {
    private static Singleton sInstance;
    public static Singleton getInstance() {
        if (sInstance == null) {//①  
            synchronized (Singleton.class) {//②
                if (sInstance == null) {
                    sInstance = new Singleton();//③  
                }
            }
        }
        return sInstance;
    }
    private Singleton() {}
}

  The setting of double check lock can avoid the 1 and 2 positions. If A thread and B thread both enter the 1 position during concurrency, but A acquires the lock, after the object is new, B repeats an instance of new after acquiring the lock , But there may still be the following problems at the 3 position, that is , the problem of instruction rearrangement :

 

   When an instance is new, the instance memory size is allocated, the object is initialized, and the process of setting the reference point is set. However, if the instruction is rearranged, it may be as shown in the figure above. Thread A allocates the instance memory size and sets the reference point to the memory space, but Since the B thread determines that the reference is not empty, it will access an empty object before the A thread initializes the object. Instead of adding another object. Therefore, you need to add the volatile keyword in front of the instance attribute to ensure thread visibility, and prohibit instruction rearrangement by setting a memory barrier.

public class Singleton {
private static volatile Singleton sInstance;
public static Singleton getInstance() {
        if (sInstance == null) {
                synchronized (Singleton.class) {
                        if (sInstance == null) {
                           sInstance = new Singleton();
                            }
                        }
                    }
                    return sInstance;
            }
private Singleton() {}
}

  

Guess you like

Origin www.cnblogs.com/dashenaichicha/p/12716480.html