About singleton

推荐实现方式[面试向]

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

// Private constructor suppresses
private Singleton() {
}

private static class LazyHolder {
static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}

JVM 在类的初始化阶段(即在 Class 被加载后,且被线程使用之前),会执行类的初始化。在执行类的初始化期间,JVM 会去获取一个锁。这个锁可以同步多个线程对同一个类的初始化。相比其他实现方案(如 double-checked locking 等),该技术方案的实现代码较为简洁,并且在所有版本的编译器中都是可行的。

Heads-up

有一种叫做 双重检查锁 (double-checked locking)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Singleton {
private static volatile Singleton INSTANCE = null;

// Private constructor suppresses
// default public constructor
private Singleton() {
}

//thread safe and performance promote
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
//when more than two threads run into the first null check same time, to avoid instanced more than one time, it needs to be checked again.
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}

此种方法只能用在 JDK5 及以后版本 (注意 INSTANCE 被声明为 volatile),之前的版本使用 “双重检查锁” 会发生非预期行为.