JAVA单例实现方式(常用)

public class Singleton {
    // Q1:为什么要使用volatile关键字?
    private volatile static Singleton uniqueInstance;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (uniqueInstance == null) {
            /* Q2:为什么要使用synchronized (Singleton.class),使用synchronized(this)或者
            synchronized(uniqueInstance)不行吗?而且synchronized(uniqueInstance)的效率更加高?*/
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                 }
            }
        }
        return uniqueInstance;
    }
}

Q1:可见的,一个地方修改所有地方同步可见并修改,使用volatile关键字会强制将修改的值立即写入主存
Q2:this 或 uniqueInstance 可能会出现空

相关文章:

  • 2021-04-02
  • 2021-12-10
  • 2021-12-03
猜你喜欢
  • 2022-02-23
  • 2022-12-23
  • 2022-01-14
  • 2021-12-23
  • 2021-12-18
  • 2021-08-26
相关资源
相似解决方案