单例模式多线程安全写法(double-lock-check)
原始版本
public static Object getInstance() { if (instance != null) { return instance; } instance = new Object(); return instance; }
不足:没有考虑多线程
版本1:
public static synchronized Object getInstance() { if (instance != null) { return instance; } instance = new Object(); return instance; }
不足:这样会导致每次调用都是同步,效率低
double-lock-check
private static final Object lock = new Object(); private static volatile Object instance; // must be declared volatile public static Object getInstance() { if (instance == null) { // avoid sync penalty if we can synchronized (lock) { // declare a private static Object to use for mutex if (instance == null) { // have to do this inside the sync instance = new Object(); } } } return instance; }
签名:删除冗余的代码最开心,找不到删除的代码最痛苦!