addcn / ideas

Dodo's 孵化器
https://github.com/addcn/ideas
1 stars 1 forks source link

单例模式最佳写法 #23

Open addcn opened 8 years ago

addcn commented 8 years ago

实际上,早在JDK1.5就引入volatile关键字,所以又有了一种更好的双重校验锁写法:

'''

public class Singleton{

private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton(){
    if(singleton == null){
        synchronized (Singleton.calss){
         if(singleton ==null){singleton = new Singleton();}
        }
    }
}

} '''

http://mp.weixin.qq.com/s?__biz=MzA4MjU5NTY0NA==&mid=404388098&idx=1&sn=8bbbba7692dca68cdda2212dec4d86c0&scene=1&srcid=0320gXPloap70ixGeYnNUaAW#wechat_redirect

Java 单例真的写对了么?

‘’‘ private static volatile SettingsDbHelper sInst = null; // <<< 这里添加了 volatile
public static SettingsDbHelper getInstance(Context context) {
SettingsDbHelper inst = sInst; // <<< 在这里创建临时变量 if (inst == null) { synchronized (SettingsDbHelper.class) { inst = sInst; if (inst == null) { inst = new SettingsDbHelper(context); sInst = inst; } } } return inst; // <<< 注意这里返回的是临时变量 } ’‘’ http://www.race604.com/java-double-checked-singleton/