三种Singleton的实现方式

本文介绍了三种不同的单例模式实现方法,包括经典的双重检查锁定(DCL)、使用ConcurrentHashMap的putIfAbsent方法以及通过AtomicBoolean结合compareAndSet方法实现线程安全的单例模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值