【发布时间】:2021-12-21 06:42:17
【问题描述】:
我看到了这个自我实现的有界blocking queue。
对其进行了更改,旨在通过将 notifyAll 替换为 notify 来消除竞争。
但我不太明白添加的 2 个额外变量有什么意义:waitOfferCount 和 waitPollCount。
它们的初始值都是0。
我的理解是,这两个变量的目的是当对象上没有 wait 时,您不会进行无用的 notify 调用。但是如果不这样做会有什么危害呢?
另一个想法是它们可能与从notifyAll 到notify 的切换有关,但我认为即使没有它们我们也可以安全地使用notify?
完整代码如下:
class FairnessBoundedBlockingQueue implements Queue {
protected final int capacity;
protected Node head;
protected Node tail;
// guard: canPollCount, head
protected final Object pollLock = new Object();
protected int canPollCount;
protected int waitPollCount;
// guard: canOfferCount, tail
protected final Object offerLock = new Object();
protected int canOfferCount;
protected int waitOfferCount;
public FairnessBoundedBlockingQueue(int capacity) {
this.capacity = capacity;
this.canPollCount = 0;
this.canOfferCount = capacity;
this.waitPollCount = 0;
this.waitOfferCount = 0;
this.head = new Node(null);
this.tail = head;
}
public boolean offer(Object obj) throws InterruptedException {
synchronized (offerLock) {
while (canOfferCount <= 0) {
waitOfferCount++;
offerLock.wait();
waitOfferCount--;
}
Node node = new Node(obj);
tail.next = node;
tail = node;
canOfferCount--;
}
synchronized (pollLock) {
++canPollCount;
if (waitPollCount > 0) {
pollLock.notify();
}
}
return true;
}
public Object poll() throws InterruptedException {
Object result;
synchronized (pollLock) {
while (canPollCount <= 0) {
waitPollCount++;
pollLock.wait();
waitPollCount--;
}
result = head.next.value;
head.next.value = null;
head = head.next;
canPollCount--;
}
synchronized (offerLock) {
canOfferCount++;
if (waitOfferCount > 0) {
offerLock.notify();
}
}
return result;
}
}
【问题讨论】:
-
不确定,但
notifyAll可能会向所有服务员发送资源可用的通知,然后所有服务员将竞争获取资源。notify只会唤醒众多服务员中的一个服务员。但是,我可能是错的。
标签: java multithreading concurrency blockingqueue