前言
阅读源码的时候总会发现大神对于单例Singleton,比如数据库连接对象,比如线程池,还有Spring的容器都有些细微的操作,但不知道啥含义,来看看优雅的(效率高数据安全的)单例怎么实现!
从最简单的开始getInstance
总是能看到getInstance方法why?一开始也不理解为啥不直接调用这个实例呢?直接访问那个实例对象就好了
随着读源码的深入萌生出几个问题:
- 访问这个实例对象的时候这个实例真的已经创建出来了吗?
- 这个实例对象是怎么创建出来的?创建的机制其实各有不同
- 比如所谓懒汉式的创建是需要依赖他这个实例的时候才会触发从而创建单例的为的是节省内存空间——没人用创建他出来干嘛?
- 所以在获取对象之前是不是有个触发的东西呢?说白了前边还有些代码逻辑实现懒汉式的思路
- 如果能够直接访问到这个实例对象怎么保证是单例呢?上次访问的和这次是同一个对象?
- 如何保证创建的是单例尤其是多线程的环境下
基于上述的问题,一个经典的实现套路:
public class MySingleton {private static MySingleton instance = new MySingleton();private Singleton() {}public static MySingleton getInstance() {return instance;}}
这样使用只需要MySingleton singleton = MySingleton.getInstance();
注意一个细节为了保证单例,这里使用static保证单例和Class对象绑定在一起所以必能访问唯一的实例
复杂单例的创建过程——用串行化的static代码块解决
拓展一下假设创建的过程很复杂可能需要别的bean来辅助即依赖别的类的实例对象辅助完成创建还有很多细节的创建过程这时应该怎么进行单例的初始化呢?
使用static代码块因为这个代码块执行顺序是严格串行的,JLS标准保证了这一点
所以不会有虚拟机优化指令重排序的问题也不会有多线程的数据安全问题
public class MySingleton {private static MySingleton instance = null;private static OtherSingleton helper = null;static{helper = OtherSingleton.getInstance();instance = MySingleton(helper);}private MySingleton(OtherSingleton helper) {if(helper) this.helper = helper;else throw new MyException("OtherSingleton getInstance failed");}public static MySingleton getInstance() {return instance;}}
可以发现static的串行化保证创建单例的时候依赖的helper是能拿得到的(这个具体由OtherSingleton 的getInstance负责这里最多加一层检查拦截抛异常)不会出现因为多线程导致创建的时候helper拿不到的情况。。
而getInstance里边也可以添加独特的东西(懒汉式后边再聊)
懒汉式(延迟创建)
基本思路,访问getInstance时
- 如果没有创建则开始创建并返回单例
已经创建则直接返回
public class MySingleton {private static MySingleton instance = null;private static OtherSingleton helper = null;private MySingleton(OtherSingleton helper) {if(helper) this.helper = helper;else throw new MyException("OtherSingleton getInstance failed");}public static MySingleton getInstance() {if(instance == null)instance = new MySingleton(OtherSingleton.getInstance());return instance;}}
但是问题在于多线程情况下这个if的判断也未必准确假设同时有两个线程都进到这个if里边执行就会创建出两个实例而不是单例而为什么有两个能进去?一个线程创建单例的时候另外一个直接进来了(那个时候单例还没创造出来
instance == null当然进的来)内存泄漏?
有人觉得java有内存回收机制没人用那个多余的单例就会被回收问题是这么执行会导致两个单例都会被用到创建的时候有多少个线程进去if里边那就有多少单例产生并被使用所以导致严重的内存泄漏!
解决方案:
认为这个if里边是个临界区域就只能有一个线程在里边才对!所以可以粗暴的使用
synchronized让整个代码块顺序执行就类似static代码块一样:public class MySingleton {private static MySingleton instance = null;private static OtherSingleton helper = null;private MySingleton(OtherSingleton helper) {if(helper) this.helper = helper;else throw new MyException("OtherSingleton getInstance failed");}public static synchronized MySingleton getInstance() {if(instance == null)instance = new MySingleton(OtherSingleton.getInstance());return instance;}}
更高的性能 double check locking
整个上锁由于锁粒度不够细导致性能比较低因此思路是尽量降低锁的粒度范围:
public class MySingleton {private static MySingleton instance = null;private static OtherSingleton helper = null;private MySingleton(OtherSingleton helper) {if(helper) this.helper = helper;else throw new MyException("OtherSingleton getInstance failed");}public static synchronized MySingleton getInstance() {if(instance == null){synchronized (MySingleton.class){if(instance == null){instance = new MySingleton(OtherSingleton.getInstance());}}}return instance;}}
这里设定MySingleton.class对象作为临界意图明显class对象唯一所以锁类这样就保证了单线程的创建实例其实和static静态块异曲同工因为static也是类初始化的时候执行的同样也是保证串行绑定了class对象的执行
可见性 volatile
但这里其实还有个问题就是创建实例对象的一瞬间真的别的线程就能立马知道了嘛(可见性)?当然是不可能的注意电脑CPU和内存的数据一致性或者说缓存一致性也是不一定有保证的毕竟存在频率(访问速率)的差异自然会存在缓存没有更新的情况
比如这里的实例对象变量instance!多线程在下一个指令周期抢到了CPU计算的时间片执行那个时候缓存默认是不更新的
除非调用java的volatile他自然是个native的关键字底层依赖C来实现变量的可见性!所以终极的程序应当是:public class MySingleton {private volatile static MySingleton instance = null;private static OtherSingleton helper = null;private MySingleton(OtherSingleton helper) {if(helper) this.helper = helper;else throw new MyException("OtherSingleton getInstance failed");}public static synchronized MySingleton getInstance() {if(instance == null){synchronized (MySingleton.class){if(instance == null){instance = new MySingleton(OtherSingleton.getInstance());}}}return instance;}}
另一种懒汉式创建单例——静态内部类
既然是懒汉式自然没办法直接用
static来创建了,但是可不可能用另外一个类的static来保证懒汉式单例呢?public class MySingleton {private MySingleton(OtherSingleton helper) {if(helper) this.helper = helper;else throw new MyException("OtherSingleton getInstance failed");}public static class MySingletonAdapter {private static final MySingleton instance = new MySingleton(OtherSingleton.getInstance());}public static getInstance() {return MySingletonAdapter.instance;}}
这种方式被称为:Initialization on demand holder
序列化单例
实现了
Serializable接口的单例序列化倒没什么问题但是反序列化时会产生新的实例对象这里得改改readResolve()方法使得返回的实例保证单例public class MySingleton {private static final long serialVersionUID = -3453453414141241L;private static MySingleton instance = new MySingleton(OtherSingleton.getInstance());private MySingleton(OtherSingleton helper) {if(helper) this.helper = helper;else throw new MyException("OtherSingleton getInstance failed");}private Object readResolve() {return instance;}}
后记
其实有没有考虑过另一个问题这里很快乐的使用了
OtherSingleton.getInstance()但是有没有想过系统刚开始一启动实例化谁先谁后呢?假设Other是后边才实例化的前边的MySingleton的创建不是吃瘪了嘛???
假设控制一个创建单例的串行顺序就好像玩游戏mod有个依赖顺序设计一个排序那看起来虽然很麻烦应该没啥问题
但是!如果两个互相依赖怎么办?OtherSingleton初始化是需要MySingleton的怎么办呢?如果几百个bean初始化的时候互相依赖该怎么解决?
这时就需要有一种思想可以用于解决各种由于依赖导致的问题——IOC(invertion of controll)控制翻转思想其实际实现是通过依赖注入dependency injection
