线程安全的单例模式

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

复制代码
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   Arts&Crafts  阅读(526)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示