/
BooleanThreadLocal.java
92 lines (86 loc) · 2.53 KB
/
BooleanThreadLocal.java
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
84
85
86
87
88
89
90
91
92
package nallar.tickthreading.util;
import nallar.tickthreading.Log;
import nallar.unsafe.UnsafeAccess;
import sun.misc.Unsafe;
/**
* Accessing a field is much faster than a normal ThreadLocal get.
* Here, we maintain a field which counts the number of threads in which the variable is true
* In most cases, this allows us to avoid the performance hit of a hashmap lookup in
* ThreadLocal.get(), assuming the variable is normally false in all threads.
*/
public class BooleanThreadLocal extends ThreadLocal<Boolean> {
@SuppressWarnings ({"FieldCanBeLocal", "FieldMayBeFinal"})
private int count = 0;
private static final Unsafe $ = UnsafeAccess.$;
private static final long index = $.objectFieldOffset(ReflectUtil.getField(BooleanThreadLocal.class, "count"));
// Unsafe magics.
@Override
public Boolean initialValue() {
return false;
}
/**
* @param value Must be Boolean.TRUE or Boolean.FALSE. No new Boolean(true/false)!
* Must always set back to false before the thread stops, else performance will be worse.
* Not going to break anything, but bad for performance.
*/
@Override
public void set(Boolean value) {
if (value == get()) {
return;
}
super.set(value);
if (value == Boolean.TRUE) {
do {
int old = $.getIntVolatile(this, index);
int next = old + 1;
if ($.compareAndSwapInt(this, index, old, next)) {
return;
}
} while (true);
} else {
do {
int old = $.getIntVolatile(this, index);
int next = old - 1;
if ($.compareAndSwapInt(this, index, old, next)) {
return;
}
} while (true);
}
}
/**
* @param value Must be Boolean.TRUE or Boolean.FALSE. No new Boolean(true/false)!
* Must always set back to false before the thread stops, else performance will be worse.
* Not going to break anything, but bad for performance.
*/
public Boolean getAndSet(Boolean value) {
Boolean oldValue = get();
if (value == oldValue) {
return oldValue;
}
super.set(value);
if (value == Boolean.TRUE) {
do {
int old = $.getIntVolatile(this, index);
int next = old + 1;
if ($.compareAndSwapInt(this, index, old, next)) {
return oldValue;
}
} while (true);
} else {
do {
int old = $.getIntVolatile(this, index);
int next = old - 1;
if ($.compareAndSwapInt(this, index, old, next)) {
return oldValue;
}
} while (true);
}
}
@Override
public Boolean get() {
if (count == 0) {
return Boolean.FALSE;
}
return super.get();
}
}