最近被问到单例模式的问题,在此做一个总结,文章分为三个大的部分:
单例是什么
在《设计模式》中给出的单例的定义是“保证一个类仅有一个实例,并提供一个访问它的全局访问点”,简单点来说就是一个类有且只有一个实例及在堆内存中只有一个,并且能够自行实例化向整个系统(当前进程其实就是JVM)提供。
从这个定义可以看出单例模式的3个特点:
- 确保自己只有一个实例
- 必须自己创建自己的实例
- 必须自行向整个系统提供这个实例
单例模式的作用是什么
- 从功能的角度看,对于系统中的某些类来说,仅有一个实例很重要,如一个系统只能有一个窗口管理器,计时工具类或者id生成器,以及日志管理,数据库等的联系管理,配置管理等,如果每个地方都去维护一个实例的话,此时就会出现状态以及数据上的混乱,如:id生成器来讲,假设只有一台服务器(不可能有单核的cpu)上多个线程都去实例化一个id生成器的类去获取id,这样生成出来的id可能是重复的或者是不符合预期的一个id或异常,所以要有一个公共的地方来统一生成id供系统全局使用,此时就需要单例模式。
- 从资源的角度看限制了实例的个数,有利于jvm进行垃圾回收,当然在获取单例的时候,为了防止并发的情况,也做了一系列检查也需要一定的开销。
单例模式的用法
懒汉式-线程不安全
最基础的实现方式,线程上下文单例,不需要共享给所有线程,也不需要加synchronize之类的锁,以提高性能。
/**
* 懒汉式 线程不安全
*/
public final class SingleInstance1 {
public static SingleInstance1 instance = null;
private SingleInstance1() {
System.out.println(Thread.currentThread().getName() + "初始化了一次");
}
public static SingleInstance1 getInstance() {
if (instance == null) {
instance = new SingleInstance1();
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
SingleInstance1.getInstance();
}, "thread" + i).start();
}
}
}
懒汉式-线程安全
加上synchronize之类保证线程安全的基础上的懒汉模式,相对性能很低,大部分时间并不需要同步。
/**
* 懒汉式 线程安全
*/
public final class SingleInstance2 {
public static SingleInstance2 instance = null;
private SingleInstance2() {
System.out.println(Thread.currentThread().getName() + "初始化了一次");
}
/**
* 同步的方法,重量级锁
*
* @return
*/
public synchronized static SingleInstance2 getInstance() {
if (instance == null) {
instance = new SingleInstance2();
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
SingleInstance2.getInstance();
}, "thread" + i).start();
}
}
}
饿汉式-线程安全
指全局的单例实例在类装载时构建,是线程安全的。
/**
* 饿汉式 线程安全
*/
public final class SingleInstance3 {
public static SingleInstance3 instance = new SingleInstance3();
private SingleInstance3() {
System.out.println(Thread.currentThread().getName() + "初始化了一次");
}
/**
* 同步的方法,重量级锁
*
* @return
*/
public static SingleInstance3 getInstance() {
if (instance == null) {
throw new IllegalStateException("not initialize");
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
SingleInstance3.getInstance();
}, "thread" + i).start();
}
}
}
双重检查锁-线程安全
在懒汉式基础上利用synchronize关键字和volatile关键字确保第一次创建时没有线程间竞争而产生多个实例,仅第一次创建时同步,性能相对较高。
/**
* 懒汉式 双重检查锁
*/
public final class SingleInstance4 {
public static volatile SingleInstance4 instance = null;
private SingleInstance4() {
System.out.println(Thread.currentThread().getName() + "初始化了一次");
}
public static SingleInstance4 getInstance() {
if (instance == null) {
synchronized (SingleInstance4.class) {//检查锁,这个地方相比上面的懒汉式锁的竞争会小一点
if (instance == null) { //再次检查
//但是这个地方可能发生指令重排,导致多个线程在外面检查实例是否为null时直接返回可能实际上实例并没有真正拿到地址
// 所以前面声明的instance加volatile修饰方式指令重排序
instance = new SingleInstance4();
}
}
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
SingleInstance4.getInstance();
}, "thread" + i).start();
}
}
}
登记式-线程安全
作为创建类的全局属性存在,创建类被装载时创建,Spring Ioc容器基本上都使用这种方式
/**
* 登记式 线程安全
* spring IOC容器大多数都使用了这种方式
*/
public final class SingleInstance5 {
private static Map<String, SingleInstance5> map = new ConcurrentHashMap<>(1);
private SingleInstance5() {
System.out.println(Thread.currentThread().getName() + "初始化了一次");
}
static {
//实际上和饿汉式一样,在类的加载的时候已经放好了
SingleInstance5 instance = new SingleInstance5();
map.put(SingleInstance5.class.getSimpleName(), instance);
}
public static SingleInstance5 getInstance(String name) {
if (name == null) {
name = SingleInstance5.class.getSimpleName();
}
if (map.get(name) == null) {
try {
//正常这个代码代码不会被执行到,要执行也只会被执行一次,类似检查
map.put(name, (SingleInstance5) Class.forName(name).newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
return map.get(name);
}
public static SingleInstance5 getInstance() {
return getInstance(null);
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
System.out.println(SingleInstance5.getInstance());
}, "thread" + i).start();
}
}
}
静态内部类方式-线程安全
效率高静态内部类在被JVM加载到内存时并不会立即实例化,在调用getInstance()方法时才加载,并实例化赋值,本身JVM在类加载阶段是同步加锁的,因此JVM保证了在同一时刻只会有一个内部类被加载。
/**
* 静态内部类 线程安全
*/
public final class SingleInstance6 {
private SingleInstance6() {
System.out.println(Thread.currentThread().getName() + "初始化了一次");
}
private static class StaticInnerClass {
private static final SingleInstance6 instance = new SingleInstance6();
}
public static SingleInstance6 getInstance() {
return StaticInnerClass.instance;
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
SingleInstance6.getInstance();
}, "thread" + i).start();
}
}
}
枚举-线程安全
java中枚举类本身也是一种单例模式,而且线程安全,还能防止在反序列化时创建新的对象。
/**
* 枚举式 线程安全
*/
public final class SingleInstance7 {
private SingleInstance7() {
System.out.println(Thread.currentThread().getName() + "初始化了一次");
}
public static SingleInstance7 getInstance(){
return SingleInstanceEnum.instance.getInstancee();
}
private enum SingleInstanceEnum {
instance;
private SingleInstance7 singleTon;
private SingleInstanceEnum() {
singleTon = new SingleInstance7();
}
private SingleInstance7 getInstancee() {
return singleTon;
}
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(() -> {
SingleInstance7.getInstance();
}, "thread" + i).start();
}
}
}