Skip to content

Commit 15a4663

Browse files
author
zhangquanli
committed
程序清单 14-2 有界缓存实现的基类
1 parent 8122f0d commit 15a4663

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package chapter_14.code_02;
2+
3+
import net.jcip.annotations.GuardedBy;
4+
import net.jcip.annotations.ThreadSafe;
5+
6+
/**
7+
* 程序清单 14-2 有界缓存实现的基类
8+
*/
9+
@ThreadSafe
10+
public class BaseBoundedBuffer<V> {
11+
@GuardedBy("this")
12+
private final V[] buf;
13+
@GuardedBy("this")
14+
private int tail;
15+
@GuardedBy("this")
16+
private int head;
17+
@GuardedBy("this")
18+
private int count;
19+
20+
protected BaseBoundedBuffer(int capacity) {
21+
this.buf = (V[]) new Object[capacity];
22+
}
23+
24+
protected synchronized final void doPut(V v) {
25+
buf[tail] = v;
26+
if (++tail == buf.length) {
27+
tail = 0;
28+
}
29+
++count;
30+
}
31+
32+
protected synchronized final V doTake() {
33+
V v = buf[head];
34+
buf[head] = null;
35+
if (++head == buf.length) {
36+
head = 0;
37+
}
38+
--count;
39+
return v;
40+
}
41+
42+
public synchronized final boolean isFull() {
43+
return count == buf.length;
44+
}
45+
46+
public synchronized final boolean isEmpty() {
47+
return count == 0;
48+
}
49+
}

0 commit comments

Comments
 (0)