public class ArrayBlockingQueue <E > extends AbstractQueue <E >
implements BlockingQueue<E>, java.io.Serializable {
final Object[] items;
/** items index for next take, poll, peek or remove */
int takeIndex;
/** items index for next put, offer, or add */
int putIndex;
int count;
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this .lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
private void enqueue(E x) {
final Object[] items = this .items;
items[putIndex] = x;
if (++putIndex == items.length)
putIndex = 0 ;
count++;
notEmpty.signal();
}
public E take() throws InterruptedException {
final ReentrantLock lock = this .lock;
lock.lockInterruptibly();
try {
while (count == 0 )
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
private E dequeue() {
final Object[] items = this .items;
@SuppressWarnings ("unchecked" )
E x = (E) items[takeIndex];
items[takeIndex] = null ;
if (++takeIndex == items.length)
takeIndex = 0 ;
count--;
if (itrs != null )
itrs.elementDequeued();
notFull.signal();
return x;
}
}