三种Singleton的实现方式

2023-05-17,,

来源: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();
}
}
}

三种Singleton的实现方式的相关教程结束。

《三种Singleton的实现方式.doc》

下载本文的Word格式文档,以方便收藏与打印。