-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathVolatileSingleton.java
More file actions
29 lines (25 loc) · 869 Bytes
/
VolatileSingleton.java
File metadata and controls
29 lines (25 loc) · 869 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package singleton;
import net.jcip.annotations.ThreadSafe;
/**
* Created by kennylbj on 2017/5/25.
* Warning: It's thread-safe unless the version of jdk is not less than 1.5
* {@see https://en.wikipedia.org/wiki/Volatile_(computer_programming)#In_Java}
* This is the thread-safe version of double-checked singleton but it limited by jdk.
* Volatile modifier will guarantee the visibility of instance.
*/
@ThreadSafe
public class VolatileSingleton {
private static volatile VolatileSingleton instance;
private VolatileSingleton() {
}
public synchronized VolatileSingleton getInstance() {
if (instance == null) {
synchronized (VolatileSingleton.class) {
if (instance == null) {
instance = new VolatileSingleton();
}
}
}
return instance;
}
}