【发布时间】:2020-04-21 01:25:52
【问题描述】:
最后阅读了优秀的Concurrency In Practice一书,我发现了BaseBoundedBuffer的清单14.2。照原样, put 和 take 方法将允许 count 超过缓冲区容量或低于 0。我知道该类是抽象的,但似乎很奇怪,这是默认行为。是否有一些充分的理由可以解释不允许计数超出容量或低于 0 的逻辑?也许像,
if(count != buf.length)
++count;
@ThreadSafe
public abstract class BaseBoundedBuffer<V> {
@GuardedBy("this") private final V[] buf;
@GuardedBy("this") private final int tail;
@GuardedBy("this") private final int head;
@GuardedBy("this") private final int count;
protected BaseBoundedBuffer (int capacity) {
this.buf = (V[]) new Object[capacity];
}
protected synchronized final void doPut(V v) {
buf[tail] = v;
if (++tail == buf.length)
tail = 0;
++count;
}
protected synchronized final V doTake() {
V v = buf[head];
buf[head] = null;
if (++head == buf.length)
head = 0;
--count;
return v;
}
public synchronized final boolean isFull() {
return count == buf.length;
}
public synchronized final boolean isEmpty() {
return count == 0;
}
}
【问题讨论】:
标签: java concurrency circular-buffer