9种Java单例模式详解
单例模式的特点
- 一个类只允许产生一个实例化对象。
- 单例类构造方法私有化,不允许外部创建对象。
- 单例类向外提供静态方法,调用方法返回内部创建的实例化对象。
懒汉式(线程不安全)
其主要表现在单例类在外部需要创建实例化对象时再进行实例化,进而达到Lazy Loading 的效果。
通过静态方法 getSingleton() 和private 权限构造方法为创建一个实例化对象提供唯一的途径。
不足:未考虑到多线程的情况下可能会存在多个访问者同时访问,发生构造出多个对象的问题,所以在多线程下不可用这种方法。
/**
* @author MrRoot
* @since 2018-12-17
* 懒汉式(线程不安全)
*/
public class Singleton {
private static Singleton singleton; private Singleton(){ } public static Singleton singleton(){
if (singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
懒汉式(线程安全,同步方法,不推荐使用)
针对懒汉式的线程不安全,自然会想到给 getSingleton() 进行 synchronized 加锁来保证线程同步。
不足:效率低。大多数情况下这个锁占用的额外资源都浪费了,每个线程在想获得类的实例时候,执行 getSingleton() 方法都要进行同步。
/**
* @author MrRoot
* @since 2019-3-27
* 懒汉式(线程安全,同步方法,不推荐使用)
*/
public class Singleton {
private static Singleton singleton; private Singleton(){ } public static synchronized Singleton singleton(){
if (singleton == null){
singleton = new Singleton();
}
return singleton;
} }
饿汉式(线程安全)
在进行类加载时完成实例化对象的过程就是饿汉式的形式。
避免了线程同步问题,在运行这个类的时候进行加载,之后直接访问
不足:相比接下来的静态内部类而言,这种方法比静态内部类多了内存常驻,容易造成内存浪费,也未达到延迟加载的效果。
/**
* @author MrRoot
* @since 2019-3-27
* 饿汉式(线程安全)
*/
public class Singleton{
private static Singleton singleton = new Singleton(); private Singleton(){ } public static Singleton singleton(){
return singleton;
}
}
静态内部类加载(线程安全)
静态内部类不会在单例加载时加载,当调用 getSingleton() 方法时才会进行加载,达到类似懒汉式效果,并且也是线程安全的。
类的静态属性只会在第一次加载类时进行初始化,所以上面的方法JVM 帮助我们保证了线程的安全性,在类进行初始化时,其他线程无法进入。
/**
* @author MrRoot
* @since 2019-3-27
* 静态内部类加载(线程安全)
*/
public class Singleton{
private static Singleton singleton; private static class SingletonInner{
private static final Singleton instance = new Singleton();
} public static Singleton getSingleton(){
return SingletonInner.instance;
}
}
枚举(线程安全)
自由串行化;保证只有一个实例;线程安全。
Effective Java 作者所提倡的方法,近乎完美,在继承场景下不适用。
/**
* @author MrRoot
* @since 2019-3-27
* 枚举(线程安全)
*/
enum Singleton{
INSTANCE; public void method(){ }
} class Test{
public static void main(String[] args) {
Singleton.INSTANCE.method();
}
}
懒汉式双重校验锁法(通常线程安全,不可保证完全安全)
使用同步代码块避免了第二种方法的效率低的问题,但此方法并不能完全起到线程同步的作用,与上面第一种方法产生的问题相似,多线程访问时可能产生多个对象。
/**
* @author MrRoot
* @since 2019-3-27
* 懒汉式双重校验锁法(通常线程安全,不可保证完全安全)
*/
class Singleton{
private static Singleton singleton; private Singleton(){ } public static Singleton singleton(){
if (singleton == null){
synchronized (Singleton.class){
if (singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
懒汉式双重检查终极版
与第六种方法不同的是,此方法给singleton 的声明上加了关键字 volatile ,进而解决了低概率的线程不安全问题。
volatile 起到禁止指令重排的作用,在它赋值完成之前,就不会调用读操作(singleton == null)。
/**
* @author MrRoot
* @since 2019-3-27
* 懒汉式双重检查终极版(volatile)
*/
class Singleton{
private static volatile Singleton singleton; private Singleton(){ } public static Singleton singleton(){
if (singleton == null){
synchronized (Singleton.class){
if (singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
使用 ThreadLocal 实现(线程安全)
ThreadLocal 会为每一个线程提供一个独立的变量副本,从而隔离了多个线程对数据的访问冲突。
对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal 采用了“以空间换时间”的方式。前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响。
/**
* @author MrRoot
* @since 2019-3-27
* 使用 ThreadLocal 实现(线程安全)
*/
class Singleton{
private static final ThreadLocal<Singleton> singleton = new
ThreadLocal<Singleton>(){
@Override
protected Singleton initialValue(){
return new Singleton();
}
}; private Singleton(){ } public static Singleton getSingleton(){
return singleton.get();
}
}
使用CAS 锁实现(线程安全)
/**
* @author MrRoot
* @since 2019-3-27
* 使用 CAS 实现(线程安全)
*/
public class Singleton {
private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>(); private Singleton(){ } public static final Singleton getSingleton(){
for (;;){
Singleton current = INSTANCE.get();
if (current != null){
return current;
}
current = new Singleton();
if (INSTANCE.compareAndSet(null,current)){
return current;
}
}
} public static void main(String[] args) {
Singleton singleton1 = Singleton.getSingleton();
Singleton singleton2 = Singleton.getSingleton();
System.out.println(singleton1 == singleton2);
}
}
最新文章
- Stream 同步错误之解决方案 ORA-00001 ORA-26787 ORA-26786
- Ajax详解及其案例分析------如何获得Ajax对象,使用Ajax对象发送GET和POST请求,校验用户名,POST和GET请求时的乱码处理,实现级联的下拉列表
- XML学习笔记(二)-- DTD格式规范
- dapper extensions (predicates)
- POJ1035——Spell checker(字符串处理)
- 对 APM 用户的一次真实调查分析(上)
- php——会话控制
- java note
- RAP在Linux 上的部署
- 拾遗与填坑《深度探索C++对象模型》3.2节
- Git 头像修改 原
- Shell 对整个文件夹中的文件进行MD5校验 [转]
- mysql 5.6.25编译安装详细步骤
- SpringBoot+MyBatis多数据源使用分页插件PageHelper
- Plus One leetcode java
- u-boot之ARM920T的start.S分析
- C++ code:低级编程
- POJ--1050--To the Max(线性动规,最大子矩阵和)
- Python3基础 str partition 以参数字符串切分字符串,只切分为三部分
- android缓存具体解释
热门文章
- [SinGuLaRiTy] 2017-07-22 NOIP2017 模拟赛
- 【转】ROWNUM与ORDER BY先后关系
- [转]关于TDD、BDD和DDD的一些看法
- jpa batch批量操作save和persist比较
- Qt 学习之路 2(22):事件总结
- CSS趣味
- apache 压缩 gzip
- C++_派生类的构造函数及派生类和基类之间的特殊关系
- P3166 [CQOI2014]数三角形
- whl is not a supported wheel on this platform解决办法