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 可能会出现空java