线程安全的单例模式
----------------------
经典的单例模式安全
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 }
使用这种方法简单易懂但效率很是低,不推荐使用。
使用急切建立实例,而不使用延迟初始化async
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; } }
使用双重检测模式,即保证了同步,有不会下降明显的性能。spa
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因此显示有点乱。code