JAVA單例模式(線程安全,高並發性能又高)


利用鎖的原理,來比較一下四種單例模式。

第一種:線程不安全,不正確

 1 class Singleton {
 2 
 3     private static Singleton instance;
 4 
 5     private Singleton() {
 6 
 7     }
 8 
 9     public static Singleton getInstance() {
10 
11         if (instance == null) {
12 
13             instance = new Singleton();
14         }
15 
16         return instance;
17     }
18 }

第二種:線程安全,但是高並發性能不是很高

 1 class Singleton {
 2 
 3     private static Singleton instance;
 4 
 5     private Singleton() {
 6 
 7     }
 8 
 9     public static synchronized Singleton getInstance() {
10 
11         if (instance == null) {
12 
13             instance = new Singleton();
14         }
15 
16         return instance;
17     }
18 }

第三種:線程安全,性能又高,這種寫法最常見。

 1 class Singleton {
 2 
 3     private static Singleton instance;
 4     private static byte[] lock = new byte[0];
 5 
 6     private Singleton() {
 7 
 8     }
 9 
10     public static Singleton getInstance() {
11 
12         if (instance == null) {
13             
14             synchronized (lock) {
15                 instance = new Singleton();
16             }
17         }
18 
19         return instance;
20     }
21 }

第四種:線程安全,性能又高,這種寫法也最為常見。

 1 class Singleton {
 2 
 3     private static Singleton instance;
 4     private static ReentrantLock lock = new ReentrantLock();
 5 
 6     private Singleton() {
 7 
 8     }
 9 
10     public static Singleton getInstance() {
11 
12         if (instance == null) {
13 
14             lock.lock();
15             if (instance == null) {
16                 instance = new Singleton();
17             }
18             lock.unlock();
19         }
20 
21         return instance;
22     }
23 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM