-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
ConcurrentUnsafeIterableArrayList.java
93 lines (78 loc) · 2.07 KB
/
ConcurrentUnsafeIterableArrayList.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
93
package nallar.collections;
import java.util.ArrayList;
import java.util.Collection;
import nallar.tickthreading.util.ReflectUtil;
import nallar.unsafe.UnsafeAccess;
import net.minecraft.tileentity.TileEntity;
import sun.misc.Unsafe;
public class ConcurrentUnsafeIterableArrayList<T> extends ArrayList<T> {
private static final Unsafe $ = UnsafeAccess.$;
private static final long elementDataIndex = $.objectFieldOffset(ReflectUtil.getField(ArrayList.class, "elementData"));
public ConcurrentUnsafeIterableArrayList(final int initialCapacity) {
super(initialCapacity);
}
public ConcurrentUnsafeIterableArrayList() {
super();
}
public ConcurrentUnsafeIterableArrayList(final Collection<? extends T> c) {
super(c);
}
public Object[] elementData() {
return (Object[]) $.getObject(this, elementDataIndex);
}
public java.util.Iterator<T> unsafeIterator() {
return new Iterator(elementData(), size());
}
public Iterable<T> unsafe() {
return new Iterable<T>() {
@Override
public java.util.Iterator<T> iterator() {
return unsafeIterator();
}
};
}
private static class Iterator<T> implements java.util.Iterator<T> {
final Object[] elementData;
int index;
private Object next;
private Object getNext() {
Object l = next;
Object o;
int i = index;
if (i == -1) {
next = null;
} else {
do {
o = elementData[i];
} while (--i != -1 && (o == null || o == l));
index = i;
next = o;
}
return l;
}
Iterator(final Object[] elementData, int start) {
this.elementData = elementData;
if (start >= elementData.length) {
start = elementData.length - 1;
}
index = start;
getNext();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
Object o = getNext();
if (o == null) {
throw new IllegalStateException("Must call hasNext before next");
}
return (T) o;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}