Make it Better
线程安全的单例模式写法
2018-1-12 StanWind



?










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;


    }


}




发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容