|
private static synchronized void syncInit() {
if (instance == null) {
instance = new GlobalConfig();
}
}
public static GlobalConfig getInstance() {
if (instance==null) {
syncInit();
}
return instance;
}
即使getInstance里面没有判断 是否null ,instance也不可能被初始化第二次
静态同步方法已经保证了其原子性 所以getInstance里面的判断只是为了第一次的初始化, 当然因为getInstance本身没有同步 所以运行速度快些,
它把同步的任务交给了 syncInit
即使多个线程同时进入 if (instance==null) { 内部 但是在调用syncInit之前
也只有第一个进入syncInit的线程会初始化instance 其他的进入后就出来了 不做任何事情
其实可以改代码为:
public static synchronized GlobalConfig getInstance() {
if (instance==null) {
instance = new GlobalConfig();
}
return instance;
}
这样子也是线程安全的 但是这样子的话以后每次都要同步运行 getInstance 运行效率会降低
所以之前的代码把getInstance和同步分离了 可以提高运行效率 只要以后线程发现instance不是null 就不会去调用那个同步化的方法了 |
|