线程安全的单例模式写法
首页 > 杂记    作者:StanWind   2018年1月12日 9:58 星期五   热度:4192°   百度已收录  
时间:2018-1-12 9:58   热度:4192° 
?
1
2
3
4
5
6
7
8
9
@ThreadSafe
public class SafeLazyInitialization {
   private static Resource resource;
   public synchronized static Resource getInstance() {
      if (resource == null)
          resource = new Resource();
      return resource;
    }
}

另外一种写法:

?
1
2
3
4
5
@ThreadSafe
public class EagerInitialization {
  private static Resource resource = new Resource();
  public static Resource getResource() { return resource; }
}

延迟初始化的写法:

?
1
2
3
4
5
6
7
8
9
@ThreadSafe
public class ResourceFactory {
    private static class ResourceHolder {
        public static Resource resource = new Resource();
    }
    public static Resource getResource() {
        return ResourceHolder.resource ;
    }
}

二次检查锁定/Double Checked Locking的写法(反模式)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class SingletonDemo {
    private static volatile SingletonDemo instance = null;//注意需要volatile
  
    private SingletonDemo() {   }
  
    public static SingletonDemo getInstance() {
        if (instance == null) { //二次检查,比直接用独占锁效率高
               synchronized (SingletonDemo .class){
                    if (instance == null) {
                               instance = new SingletonDemo ();
                    }
             }
        }
        return instance;
    }
}
二维码加载中...
本文作者:StanWind      文章标题: 线程安全的单例模式写法
本文地址:https://www.stanwind.com/post/67
版权声明:若无注明,本文皆为“Make it Better”原创,转载请保留文章出处。

返回顶部    首页    手机版本    后花园  
版权所有:Make it Better    站长: StanWind    赣ICP备17014296号