-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMutableQueue.java
83 lines (66 loc) · 2.39 KB
/
MutableQueue.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
package example6;
import common.Optional;
import common.Pair;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
public final class MutableQueue<T> {
private final AtomicReference<ImmutableQueue<T>> ref;
public MutableQueue() {
ref = new AtomicReference<>(new ImmutableQueue<T>());
}
public void enqueue(T value) {
boolean isSuccess;
do {
ImmutableQueue<T> current = ref.get();
ImmutableQueue<T> update = current.enqueue(value);
isSuccess = ref.compareAndSet(current, update);
} while(!isSuccess);
synchronized (ref) {
ref.notify();
}
}
public Optional<T> dequeue() {
while (true) {
ImmutableQueue<T> current = ref.get();
if (current.isEmpty())
return Optional.absent();
Pair<Optional<T>, ImmutableQueue<T>> result = current.dequeue();
if (ref.compareAndSet(current, result.collection()))
return result.value();
}
}
public T dequeueAwait() throws TimeoutException {
return awaitDequeue(TimeUnit.SECONDS, 10);
}
public T awaitDequeue(TimeUnit unit, int value) throws TimeoutException {
long timeout = System.currentTimeMillis() + unit.toMillis(value);
Optional<T> result = Optional.absent();
while (result.isAbsent()) {
if (timeout <= System.currentTimeMillis())
throw new TimeoutException("dequeueAwait");
result = dequeue();
if (result.isAbsent())
try {
synchronized (ref) {
if (ref.get().isEmpty())
ref.wait(300);
}
}
catch (InterruptedException ignored) {}
}
return result.get();
}
public void awaitEmpty(TimeUnit unit, int value)
throws InterruptedException, TimeoutException {
long timeout = System.currentTimeMillis() + unit.toMillis(value);
while (!ref.get().isEmpty()) {
if (timeout <= System.currentTimeMillis())
throw new TimeoutException("dequeueAwait");
synchronized (ref) {
if (!ref.get().isEmpty())
ref.wait(300);
}
}
}
}