三种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();
- }
- }
- }