-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathGrumpyBoundedBuffer.java
56 lines (47 loc) · 1.25 KB
/
GrumpyBoundedBuffer.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
package net.jcip.examples;
import net.jcip.annotations.*;
/**
* GrumpyBoundedBuffer
* <p/>
* Bounded buffer that balks when preconditions are not met
*
* @author Brian Goetz and Tim Peierls
*/
@ThreadSafe
public class GrumpyBoundedBuffer <V> extends BaseBoundedBuffer<V> {
public GrumpyBoundedBuffer() {
this(100);
}
public GrumpyBoundedBuffer(int size) {
super(size);
}
public synchronized void put(V v) throws BufferFullException {
if (isFull())
throw new BufferFullException();
doPut(v);
}
public synchronized V take() throws BufferEmptyException {
if (isEmpty())
throw new BufferEmptyException();
return doTake();
}
}
class ExampleUsage {
private GrumpyBoundedBuffer<String> buffer;
int SLEEP_GRANULARITY = 50;
void useBuffer() throws InterruptedException {
while (true) {
try {
String item = buffer.take();
// use item
break;
} catch (BufferEmptyException e) {
Thread.sleep(SLEEP_GRANULARITY);
}
}
}
}
class BufferFullException extends RuntimeException {
}
class BufferEmptyException extends RuntimeException {
}