/
DenizenAtomicIntegerFieldUpdater.java
63 lines (49 loc) · 1.85 KB
/
DenizenAtomicIntegerFieldUpdater.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
package net.aufdemrand.denizen.utilities;
import net.aufdemrand.denizen.utilities.debugging.dB;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
public class DenizenAtomicIntegerFieldUpdater<T> extends AtomicIntegerFieldUpdater<T> {
private static final Unsafe unsafe;
static {
Unsafe theUnsafe = null;
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
theUnsafe = (Unsafe) field.get(null);
}
catch (Exception e) {
dB.echoError(e);
}
unsafe = theUnsafe;
}
private final long offset;
public DenizenAtomicIntegerFieldUpdater(Field field) {
field.setAccessible(true);
int modifiers = field.getModifiers();
Class fieldt = field.getType();
if (fieldt != int.class) {
throw new IllegalArgumentException("Must be integer type");
}
if (!Modifier.isVolatile(modifiers)) {
throw new IllegalArgumentException("Must be volatile type");
}
offset = unsafe.objectFieldOffset(field);
}
public boolean compareAndSet(T obj, int expect, int update) {
return unsafe.compareAndSwapInt(obj, offset, expect, update);
}
public boolean weakCompareAndSet(T obj, int expect, int update) {
return unsafe.compareAndSwapInt(obj, offset, expect, update);
}
public void set(T obj, int newValue) {
unsafe.putIntVolatile(obj, offset, newValue);
}
public void lazySet(T obj, int newValue) {
unsafe.putOrderedInt(obj, offset, newValue);
}
public final int get(T obj) {
return unsafe.getIntVolatile(obj, offset);
}
}