三种Singleton的实现方式

简介:

来源:http://melin.iteye.com/blog/838258

三种Singleton的实现方式,一种是用大家熟悉的DCL,另外两种使用cas特性来实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;    
     }    
}   

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
  * 利用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; 
    

 

本文转自夏雪冬日博客园博客,原文链接:XXXXXX,如需转载请自行联系原作者
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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(); 
        
    
}



 


本文转自夏雪冬日博客园博客,原文链接:http://www.cnblogs.com/heyonggang/p/6104677.html,如需转载请自行联系原作者
目录
相关文章
|
Java 数据库 数据安全/隐私保护
基于Java的公务员考试资料共享平台的设计与实现
基于Java的公务员考试资料共享平台的设计与实现
365 0
|
Java Maven Spring
【Spring】EL表达式失效的问题(添加 isELIgnored)
【Spring】EL表达式失效的问题(添加 isELIgnored)
PDF-XChange 注册码
PDF-XChange Viewer Pro 注册码: User Name     : Team EAT Organization   : EATiSO Email address : teameat@no_email.com Key code         : PXP50-6TUFA-Z4R48-3H1KG-IXM7Z-6TLLP PDF-XChange简介:百度百科
7103 0
|
缓存 Java 数据库
springboot数据库及缓存常用依赖及配置
springboot数据库及缓存常用依赖及配置
205 9
|
存储 缓存 资源调度
npm、yarn与pnpm详解
npm、yarn与pnpm详解
415 0
BUUCTF---web---[GXYCTF2019]BabyUpload
BUUCTF---web---[GXYCTF2019]BabyUpload
|
存储 安全 生物认证
【网络安全 | 指纹识别工具】WhatWeb使用详析
【网络安全 | 指纹识别工具】WhatWeb使用详析
1216 0
【网络安全 | 指纹识别工具】WhatWeb使用详析
|
存储 算法 Java
Go入门篇:(二)基础知识之结构,包,变量初探
Go入门篇:(二)基础知识之结构,包,变量初探
273 0
|
存储 缓存 算法
MIPS架构深入理解1-MIPS和RISC架构体系介绍
MIPS架构深入理解1-MIPS和RISC架构体系介绍