线程安全的单例模式的几种实现方法分享
生活随笔
收集整理的這篇文章主要介紹了
线程安全的单例模式的几种实现方法分享
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、餓漢式單例
?
1 public class Singleton { 2 private final static Singleton INSTANCE = new Singleton(); 3 4 5 private Singleton() { } 6 7 public static Singleton getInstance() { 8 return INSTANCE; 9 } 10 }?
2、借助內部類
屬于懶漢式單例,因為Java機制規定,內部類SingletonHolder只有在getInstance()方法第一次調用的時候才會被加載(實現了lazy),而且其加載過程是線程安全的。內部類加載的時候實例化一次instance。
3、普通加鎖解決
1 public class Singleton { 2 3 4 private Singleton() { } 5 6 7 private static class SingletonHolder { 8 private final static Singleton INSTANCE = new Singleton(); 9 } 10 11 public static Singleton getInstance() { 12 return SingletonHolder.INSTANCE; 13 } 14 }?
雖然解決了線程安全問題,但是每個線程調用getInstance都要加鎖,我們想要只在第一次調用getInstance時加鎖,請看下面的雙重檢測方案
4、雙重檢測,但要注意寫法
public class Singleton {private static Singleton instance = null;private Singleton() { }public static Singleton getInstance() {if(instance == null) {synchronzied(Singleton.class) {Singleton temp = instance;if(temp == null) {temp = new Singleton();instance = temp}}}return instance;} }?
由于指令重排序問題,所以不可以直接寫成下面這樣:
1 public class Singleton { 2 private static Singleton instance = null; 3 4 private Singleton() { } 5 6 public static Singleton getInstance() { 7 if(instance == null) { 8 synchronzied(Singleton.class) { 9 if(instance == null) { 10 instance = new Singleton(); 11 } 12 } 13 } 14 15 return instance; 16 } 17 }?
但是如果instance實例變量用volatile修飾就可以了,volatile修飾的話就可以確保instance = new Singleton();對應的指令不會重排序,如下的單例代碼也是線程安全的:
1 public class Singleton { 2 private static volatile Singleton instance = null; 3 4 private Singleton() { } 5 6 public static Singleton getInstance() { 7 if(instance == null) { 8 synchronzied(Singleton.class) { 9 if(instance == null) { 10 instance = new Singleton(); 11 } 12 } 13 } 14 15 return instance; 16 } 17 }?
?
您可能感興趣的文章:
轉載于:https://www.cnblogs.com/blog-cq/p/5648856.html
總結
以上是生活随笔為你收集整理的线程安全的单例模式的几种实现方法分享的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 复合非聚集索引里列的顺序的重要性
- 下一篇: Android中asset和raw的区别