-
Notifications
You must be signed in to change notification settings - Fork 1
/
LockQueue.java
75 lines (67 loc) · 1.89 KB
/
LockQueue.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 in.xnnyygn.concurrent.mylock;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.concurrent.atomic.AtomicReference;
class LockQueue {
final AtomicReference<Node> head = new AtomicReference<>();
final AtomicReference<Node> tail = new AtomicReference<>();
@Nonnull
Node enqueue(@Nonnull Node node) {
Node t;
while (true) {
t = tail.get();
if (t == null) {
Node sentinel = Node.createSentinel();
if (head.compareAndSet(null, sentinel)) {
tail.set(sentinel);
}
} else {
node.predecessor.lazySet(t);
if (tail.compareAndSet(t, node)) {
t.successor.set(node);
return t;
}
}
}
}
boolean isFirstCandidate(@Nonnull Node node) {
return node.predecessor.get() == head.get();
}
@Nullable
Node findNormalSuccessor(@Nonnull Node node) {
Node s = node.successor.get();
if (s != null && s.isAborted()) {
return s;
}
s = null;
Node c = tail.get();
while (c != node) {
if (!c.isAborted()) {
s = c;
}
c = c.predecessor.get();
}
return s;
}
@Nonnull
Node skipAbortedPredecessor(@Nonnull Node node) {
Node h = head.get();
Node p = node.predecessor.get();
Node c = p;
while (c != h && c.isAborted()) {
c = c.predecessor.get();
}
if (c != p) {
node.predecessor.set(c);
}
return c;
}
boolean contains(@Nonnull Node node) {
for (Node c = tail.get(); c != null; c = c.predecessor.get()) {
if (node == c) {
return true;
}
}
return false;
}
}