來源:http://melin.iteye.com/blog/838258
三種Singleton的實現方式,一種是用大家熟悉的DCL,另外兩種使用cas特性來實現。
public class LazySingleton { private static volatile LazySingleton instance; public static LazySingleton getInstantce() { if (instance == null) { synchronized (LazySingleton.class) { if (instance == null) { instance = new LazySingleton(); } } } return instance; } }
/** * 利用putIfAbsent執行緒安全操作,實現單例模式 * * @author Administrator * */ public class ConcurrentSingleton { private static final ConcurrentMap<String, ConcurrentSingleton> map = new ConcurrentHashMap<String, ConcurrentSingleton>(); private static volatile ConcurrentSingleton instance; public static ConcurrentSingleton getInstance() { if (instance == null) { instance = map.putIfAbsent("INSTANCE", new ConcurrentSingleton()); } return instance; } }
public class AtomicBooleanSingleton { private static AtomicBoolean initialized = new AtomicBoolean(false); private static volatile AtomicBooleanSingleton instance; public static AtomicBooleanSingleton getInstantce() { checkInitialized(); return instance; } private static void checkInitialized() { if(instance == null && initialized.compareAndSet(false, true)) { instance = new AtomicBooleanSingleton(); } } }