第一種方式:通過synchronized解決,性能下降 1 package singleton; 2 3 public class Singleton { 4 private Singleton() { 5 } 6 7 private static Singleton instance ; 8 9 ...
第一種方式:通過synchronized解決,性能下降
1 package singleton; 2 3 public class Singleton { 4 private Singleton() { 5 } 6 7 private static Singleton instance ; 8 9 public static synchronized Singleton getInstance() { 10 if (instance == null) { 11 synchronized (instance) { 12 instance = new Singleton(); 13 } 14 } 15 return instance; 16 } 17 }View Code
第二種方式:JVM載入這個類時馬上創建唯一的單件,可能創建時負擔太重而該單件未使用,造成浪費.
1 package singleton; 2 3 public class Singleton { 4 private Singleton() { 5 } 6 7 private static Singleton instance = new Singleton(); 8 9 public static Singleton getInstance() { 10 return instance; 11 } 12 }View Code
第三種方式:雙重檢查加鎖
1 package singleton; 2 3 public class Singleton { 4 private Singleton() { 5 } 6 7 /** 8 * volatile確保當instance被初始化成Singleton實例時,多個線程正確的處理instance變數 9 */ 10 private volatile static Singleton instance; 11 12 public static Singleton getInstance() { 13 if (instance != null) { 14 synchronized (Singleton.class) { 15 if (instance != null) { 16 instance = new Singleton(); 17 } 18 } 19 } 20 return instance; 21 } 22 }View Code