public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) instance = new LazySingleton(); // 多線程下會創建多個實例
return instance;
}
}
public synchronized static LazySingleton getInstance() { ... }
public class LazySingleton {
private static volatile LazySingleton instance; // volatile 禁止指令重排
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) { // 第一次檢查,無鎖讀取
synchronized (LazySingleton.class) {
if (instance == null) { // 第二次檢查,鎖內創建
instance = new LazySingleton();
}
}
}
return instance;
}
}
關鍵點:volatile 確保 instance = new ... 的寫入對其他執行緒可見,避免半初始化物件被返回。
public class Singleton {
private Singleton() {}
private static class Holder {
static final Singleton INSTANCE = new Singleton(); // 類載入時初始化,JVM 保證線程安全
}
public static Singleton getInstance() { return Holder.INSTANCE; }
}
優點:利用類載入機制天然線程安全、延遲載入 (調用 getInstance 才載入 Holder)、代碼簡潔無鎖。
public class ThreadPoolFactoryUtil {
private ExecutorService executorService;
private ThreadPoolFactoryUtil() {
int nThreads = Runtime.getRuntime().availableProcessors();
executorService = Executors.newFixedThreadPool(nThreads);
}
private static class SingletonContainer {
static final ThreadPoolFactoryUtil INSTANCE = new ThreadPoolFactoryUtil();
}
public static ThreadPoolFactoryUtil getUtil() { return SingletonContainer.INSTANCE; }
public ExecutorService getExecutorService() { return executorService; }
}
在高併發循環任務中,透過單例確保全域僅有一個線程池,避免資源耗盡。