Design Mode - double checks the lock of singleton

Single-mode embodiment, there are two, and starving formula lazy formula.

Lazy man's encounter thread-safety issues in the case of multi-threading, resulting in singleton failure.

The solution is to increase the lock to prevent multiple threads repeated initialization. Is also to avoid the locked situations every request, it will be locked at the same time, increased checks to prevent locking operation every time, increase throughput. However, the JVM according to their optimization, some instructions are rearranged, in this case, reference will lead to failure. So by increasing the need to prevent the volatile keyword command rearrangement.

 

The final DEMO as follows:

public class Singleton {
    private volatile static Singleton uniqueSingleton;

    private Singleton() {
    }

    public Singleton getInstance() {
        if (null == uniqueSingleton) {
            synchronized (Singleton.class) {
                if (null == uniqueSingleton) {
                    uniqueSingleton = new Singleton();
                }
            }
        }
        return uniqueSingleton;
    }
}

 

Transfer: https: //blog.csdn.net/e31006/article/details/85861791

Guess you like

Origin www.cnblogs.com/kinglovelqn/p/11962836.html