-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStableValue.java
More file actions
83 lines (71 loc) · 1.81 KB
/
StableValue.java
File metadata and controls
83 lines (71 loc) · 1.81 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package jdk.sandbox.internal.util.json;
import java.util.function.Supplier;
/// Mimics JDK's StableValue using double-checked locking pattern
/// for thread-safe lazy initialization.
class StableValue<T> {
private volatile T value;
private final Object lock = new Object();
private StableValue() {
}
public static <T> StableValue<T> of() {
return new StableValue<>();
}
public T orElse(T defaultValue) {
T result = value;
return result != null ? result : defaultValue;
}
public T orElseSet(Supplier<T> supplier) {
T result = value;
if (result == null) {
synchronized (lock) {
result = value;
if (result == null) {
value = result = supplier.get();
}
}
}
return result;
}
public void setOrThrow(T newValue) {
if (value != null) {
throw new IllegalStateException("Value already set");
}
synchronized (lock) {
if (value != null) {
throw new IllegalStateException("Value already set");
}
value = newValue;
}
}
public static <T> Supplier<T> supplier(Supplier<T> supplier) {
return new Supplier<>() {
private volatile T cached;
private final Object supplierLock = new Object();
@Override
public T get() {
T result = cached;
if (result == null) {
synchronized (supplierLock) {
result = cached;
if (result == null) {
cached = result = supplier.get();
}
}
}
return result;
}
@Override
public String toString() {
return get().toString();
}
@Override
public int hashCode() {
return get().hashCode();
}
@Override
public boolean equals(Object obj) {
return get().equals(obj);
}
};
}
}