我正在尝试使用固定长度的字节数组数组来自定义阻塞队列的实现。我没有删除轮询元素,因此我调整了 put 方法以返回字节数组,以便可以直接写入(生产者线程使用 MappedByteBuffer 直接写入此字节数组)。我添加了“commitPut()”方法来简单地增加计数器并设置“长度”数组。(如果多个线程正在写入,这可能是并发问题,但我知道只有一个线程正在写入)。
以下是我目前拥有的。如果我逐步调试它会起作用,但是如果我“运行”它看起来会遇到一些锁定问题。我复制、剥离和调整了 ArrayBlockingQueue 代码。有更好知识的人可以看看课程并告诉我我做错了什么,或者如何做得更好(比如直接写入缓冲区并在同一步骤设置长度数组和计数器)?
public class ByteArrayBlockingQueue {
private final int[] lens; // array to valid lengths
private final byte[][] items; // array of byte arrays
private int takeIndex = 0;
private int putIndex = 0;
private int count = 0;
public volatile int polledLen = 0; // lenght of last polled byte array
private final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
final int inc(int i) {
return (++i == items.length)? 0 : i;
}
public ByteArrayBlockingQueue(int capacity, int size, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new byte[capacity][size];
this.lens = new int[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
public byte[] put() throws InterruptedException {
final byte[][] items = this.items;
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == items.length)
notFull.await();
} catch (InterruptedException ie) {
notFull.signal(); // propagate to non-interrupted thread
throw ie;
}
//insert(e, len);
return items[putIndex];
} finally {
lock.unlock();
}
}
public void commitPut(int lenBuf) throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
lens[putIndex] = lenBuf;
putIndex = inc(putIndex);
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public byte[] poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count == 0)
return null;
final byte[][] items = this.items;
final int[] lens = this.lens;
byte[] e = items[takeIndex];
this.polledLen = lens[takeIndex];
//items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return e;
} finally {
lock.unlock();
}
}
}