单例模式

单例模式的特点

  • 单例类只能有一个实例
  • 单例类必须创建自己唯一的实例
  • 单例类必须给其他对象提供这一实例

饿汉 vs 懒汉

  • 饿汉:声明实例引用时即实例化
  • 懒汉:静态方法第一次被调用前不实例化,也即懒加载。对于创建实例代价大,且不定会使用时,使用懒加载可以减少开销

解决方案

在多线程环境中能工作,但是效率不高,不建议面试采用(懒汉)

1
2
3
4
5
6
7
8
9
10
public class Singleton1 {
private Singleton1 {}
private static Singleton1 instance;
public static synchronized Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
}
  • 优点:线程安全,可确保正常使用(不考虑通过反射调用私有构造方法),只有一个实例
  • 缺点:每次获取实例都需要申请锁,开销大,效率低

加同步锁前后两次判断实例是否存在(懒汉)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton2 {
private Singleton2() {}
private static Singleton2 instance;
public static Singleton2 getInstance() {
if(instance == null) {
synchronized(Singleton2.class) {
if (instance == null) {
instance = new Singleton2();
}
}
}
return instance;
}
}
  • 优点:不需要在每次调用时加锁,效率比上一个高
  • 缺点:虽然使用了synchronized,但本质上是线程不安全的

双重检查(Double Check)下的懒汉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Singleton3 {
private static volatile Singleton3 instance;
private Singleton3() {}
public static Singleton3 getInstance() {
if (instance == null) {
synchronized(Singleton3.class) {
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}
  • 优点:使用了双重检查,避免了线程不安全,同时避免了不必要的锁开销
  • 缺点:无
  • 注意:使用volatile关键字的目的不是保证可见性(synchronized已经保证了可见性),而是为了保证顺序性。具体来说,instance = new Singleton3()不是原子操作,实际上被拆分为了三步:1) 分配内存;2) 初始化对象;3) 将instance指向分配的对象内存地址。 如果没有volatile,可能会发生指令重排序,使得instance先指向内存地址,而对象尚未初始化,其它线程直接使用instance引用进行对象操作时出错。详细原理可参见《双重检查锁定与延迟初始化

利用静态变量(饿汉)

1
2
3
4
5
6
7
public class Singleton4 {
private Singleton4() {}
private static Singleton4 instance = new Singleton4();
public static Singleton4 getInstance() {
return instance;
}
}
  • 优点:实现简单,无线程同步问题
  • 缺点:在类装载时完成实例化。若该实例一直未被使用,则会造成资源浪费

利用静态代码块(饿汉)

1
2
3
4
5
6
7
8
9
10
public class Singleton5 {
private static Singleton5 instance;
private Singleton5() {}
static {
instance = new Singleton5();
}
public static Singleton5 getInstance() {
return instance;
}
}
  • 优点:实现简单,无线程同步问题
  • 缺点:在类装载时完成实例化。若该实例一直未被使用,则会造成资源浪费

实现按需创建实例(强烈推荐)(懒汉)

1
2
3
4
5
6
7
8
9
public class Singleton6 {
private Singleton6() {}
private static class Nested {
private static Singleton6 instance = new Singleton6();
}
public static Singleton6 getInstance() {
return Nested.instance;
}
}
  • 优点:无线程同步问题,实现了懒加载。因为只有调用getInstance()时才会装载内部类,才会创建实例。同时因为使用内部类,先调用内部类的线程会获得类初始化锁,从而保证内部类的初始化(包括实例化它所引用的外部类对象)线程安全。即使内部类创建外部类的实例Singleton6 instance = new Singleton6()发生指令重排也不会引起双重检查下的懒汉模式中提到的问题,因此无须使用volatile关键字。
  • 缺点:无

参考资料


Author: Toyan
Link: https://toyan.top/singleton-mode/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
支付宝打赏
微信打赏