线程安全的单例模式

  
                       线程安全的单例模式
                      ----------------------
经典的单例模式

1 public class Singleton{
2       private static Singleton uniqueInstance;
3       private static Singleton(){}
4       public  static Singleton getInstance(){
5           if(uniqueInstance == null)
6              uniqueInstance = new Singleton()
7           return uniqueInstance;
8       }
9   }

 

经典的单例模式是线程不安全的,如果多个并发线程同时调用getInstance()方法就有可能生成多个实例。下面介绍几种实现线程安全的单例模式
使用synchronized修饰getInstance()方法

1 public class Singleton{
2   private static Singleton uniqueInstance;
3   private static Singleton(){}
4   public  static synchronized Singleton getInstance(){
5       if(uniqueInstance == null)
6          uniqueInstance = new Singleton()
7       return uniqueInstance;
8   }
9 }

 


使用这种方法简单易懂但效率非常低,不推荐使用。
使用急切创建实例,而不使用延迟初始化

1 public class Singleton{
2   private static Singleton uniqueInstance = new Singleton();
3   private static Singleton(){}
4   public  static Singleton getInstance(){
5       return uniqueInstance;
6  }
7 }

 


如果创建该实例不是那么昂贵的话,就使用该模式吧。
如果出于性能考虑而需要使用延迟初始化,就使用 lazy initialization holder class模式,这种模式也被称为initialize-demand holder class idiom,保证了实例要被创建的时候才初始化。

public class Singleton{
  private static class SingletonHolder{
         private static Singleton uniqueInstance = new Singleton();
  }
  private static Singleton(){}
  public  static Singleton getInstance(){
      return SingletonHolder.uniqueInstance;
 }
}

 


使用双重检测模式,即保证了同步,有不会降低明显的性能。

 1 public class Singleton{
 2   private static Singleton uniqueInstance;
 3   private staticSingleton(){}
 4   public  static Singleton getInstance(){
 5       if(uniqueInstance == null){
 6           asynchronized(Singleton.class){
 7               if(uniqueInstance == null){
 8                   uniqueInstance = new Singleton()
 9               }
10           }
11       }
12  }
13      return  uniqueInstance;
14 }

 


这几种模式推荐使用3或者4,更或者直接使用模式3,即保证了线程的安全,又没有任何性能的降低,而且提供了延迟初始化。

 

 

不支持Marketdown所以显示有点乱。

posted on 2014-04-23 22:01  Arts&Crafts  阅读(522)  评论(0编辑  收藏  举报

导航