-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
CounterThreadLocalAssumeZero.java
75 lines (67 loc) · 1.82 KB
/
CounterThreadLocalAssumeZero.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
package nallar.tickthreading.util;
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 CounterThreadLocalAssumeZero extends ThreadLocal<Integer> {
@SuppressWarnings({"FieldCanBeLocal", "FieldMayBeFinal", "CanBeFinal"})
private int count = 0;
private static final Unsafe $ = UnsafeAccess.$;
private static final long index = $.objectFieldOffset(ReflectUtil.getField(CounterThreadLocalAssumeZero.class, "count"));
// Unsafe magics.
@Override
public Integer initialValue() {
return 0;
}
@Override
public Integer get() {
throw new UnsupportedOperationException();
}
public int getCount() {
if (count == 0) {
return 0;
}
return super.get();
}
@Override
public void set(Integer value) {
throw new UnsupportedOperationException();
}
public int increment() {
int count = getCount();
int n = count + 1;
set(n);
if (count == 0) {
do {
int old = $.getIntVolatile(this, index);
int next = old + 1;
if ($.compareAndSwapInt(this, index, old, next)) {
return 1;
}
} while (true);
}
return n;
}
public int decrement() {
int count = getCount();
if (count == 0) {
throw new Error("Can not decrement counter below 0.");
}
int n = count - 1;
set(n);
if (count == 1) {
do {
int old = $.getIntVolatile(this, index);
int next = old - 1;
if ($.compareAndSwapInt(this, index, old, next)) {
return 0;
}
} while (true);
}
return n;
}
}