Repository navigation
Expand file tree
/
Copy pathBlockingQueue.java
More file actions
107 lines (89 loc) · 2.02 KB
/
Copy pathBlockingQueue.java
File metadata and controls
107 lines (89 loc) · 2.02 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package org.kuppe;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public final class BlockingQueue<E> {
private final E[] store;
private final ReentrantLock lock;
private final Condition waitC;
private final Condition waitP;
private int head;
private int tail;
private int size;
@SuppressWarnings("unchecked")
public BlockingQueue(final int capacity) {
this.store = (E[]) new Object[capacity];
// see BlockingQueueSplit.tla
this.lock = new ReentrantLock();
this.waitC = lock.newCondition();
this.waitP = lock.newCondition();
}
/**
* Add the given element to this queue waiting if necessary for space to become
* available.
*
* @see {@link BlockingQueue#take()}.
*/
public void put(final E e) throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
while (isFull()) {
waitP.await();
}
waitC.signal();
// Add e and do bookkeeping.
append(e);
} finally {
lock.unlock();
}
}
/**
* Remove an element E from this queue, waiting if necessary until an element
* becomes available.
*
* @see {@link BlockingQueue#put(Object)}.
*/
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
while (isEmpty()) {
waitC.await();
}
waitP.signal();
// Remove e and do bookkeeping.
return head();
} finally {
lock.unlock();
}
}
//****** auxiliary methods ******//
private void append(final E e) {
store[tail] = e;
tail = next(tail);
size++;
}
private E head() {
final E e = store[head];
store[head] = null;
head = next(head);
size--;
return e;
}
private int next(final int x) {
return (x + 1) % store.length;
}
/**
* @return true if this buffer has reached its capacity defined during
* instantiation.
*/
private boolean isFull() {
return size == this.store.length;
}
/**
* @return true iff this buffer contains no elements E.
*/
private boolean isEmpty() {
return size == 0;
}
}