三种Singleton的实现方式
来源: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();  
            }  
        }  
    }  
微信公众号:
猿人谷 
如果您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】
如果您希望与我交流互动,欢迎关注微信公众号
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
                    
                
                
            
        
浙公网安备 33010602011771号