线程安全的Singleton要点

1、privat static Singleton 要加votatile关键字修饰,防止对象的初始化代码与引用赋值代码进行重排序。

2、getInstance方法,最外层要加if (instance == null),然后加锁synchronized,然后再加if (instance == null)的判断

3、内层if (instance == null) 判断的作用是,如果没有这个内层的判断,多个线程都进入了外层的if (instance == null) 判断,并在锁的地方等待,那么势必会依次创建N个重复的对象,不是单例了。

示例代码如下:

public class Singleton {

    // 通过volatile关键字的使用,防止编译器将
    // 1、初始化对象,2、给对象引用赋值
    // 这两步进行重排序
    private static volatile Singleton instance = null;

    private Singleton() {

    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (instance) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}
原文地址:https://www.cnblogs.com/shuada/p/9833274.html