关于单例模式你应该知道的

单例模式

使用场景:

  • Hibernate使用时只需要一个SessionFactory
  • 在Spring中,指定scope=”singleton”则bean为单例(不指定也默认单例)
  • 业务逻辑组件、DAO组件、数据源组件都是单例,因为它们无需保存用户的状态
  • 数据连接池使用单例模式,无需创建多个

优势:

  • 减少创建对象带来的系统开销
  • 便于管理单个对象的生命周期

写法:

  • 懒汉式,即Lazy Loading,什么时候用什么时候初始化,需要考虑线程同步
  • 饿汉式,即在类装载的时候就完成实例化,避免了考虑线程同步

第一种:饿汉式,线程安全

1
2
3
4
5
6
7
8
9
10
public class Singleton {

private final static Singleton singleton = new Singleton();

private Singleton(){}

public static Singleton getInstance(){
return singleton;
}
}

第二种:懒汉式,线程不安全(虽然使用了synchronized,但无法完全保证线程同步)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Singleton {

private static Singleton singleton;

private Singleton() {}

public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
singleton = new Singleton();
}
}
return singleton;
}
}

第三种:懒汉式,双重检查,线程安全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Singleton {

private static volatile Singleton singleton;

private Singleton() {}

public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}

第四种:ThreadLocal写法,线程安全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Manager {

private static final ThreadLocal<Manager> sManager = new ThreadLocal<Manager>() {
@Override
protected Manager initialValue() {
return new Manager();
}
};

private Manager() {

}

public static Manager getInstance() {
return sManager.get();
}
}