[Singleton] volatile role lazy type of thread-safety issues

Original link: https://blog.csdn.net/Activity_Time/article/details/96496579
******

1. The lazy man's Java implementation
public class Singleton {

    // 唯一实例
    private volatile static Singleton instance = null;

    // 私有构造
    private Singleton() {
        System.out.println("Singleton构造" + this);
    }

    // 获取实例
    synchronized public static Singleton getInstance() {
        return instance == null ? (instance = new Singleton()) : instance;
    }

}
Singleton pattern of multi-threaded environment under 2 thread safety issues:

Starving mode Singleton pattern: In a multi-threaded environment, thread-safe
lazy mode singleton mode: In a multi-threaded environment, thread safe

Apparently due to the operation of atomic sentence air and create objects and wrong, dirty reads and other problems will occur in multi-threaded scenarios
need to synchronize the process, as well as ensure that the update notification variables to other threads to use the volatile keyword

3. volatile keyword (thread visibility)

Detailed keyword in Java Volatile: https://www.cnblogs.com/zhengbin/p/5654805.html#_label1
Java Memory Model: https://www.cnblogs.com/zhengbin/p/6407137.html
Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/ACTIM/p/11230105.html