gpt4 book ai didi

java - 了解关闭时的关闭请求标志

转载 作者:行者123 更新时间:2023-11-30 02:58:35 25 4
gpt4 key购买 nike

我正在阅读 B. Goetz JCIP,并在第 7.2 节中发现了有关 cancellin 基于线程的服务的一些误解。代码如下:

public class LogWriter{

private final BlockingQueue<String> queue;
private final LoggerThread logger;

public LogWriter(Writer writer){
this.queue = new LinkedBlockingQueue<String>(CAPACITY);
this.logger = new LoggerThread(writer);
}

public void start(){ logger.start(); }

public void log(String msg) throws InterruptedException {
queue.put(msg);
}

private class LoggerThread extends Thread {
private final PrintWriter writer;
public void run() {
try{
while(true)
writer.println(queue.take());
} catch(InterruptedException ignored){
} finally {
writer.close();
}
}
}

他说此类服务不提供终止方式。他给出了另一种替代方案:

public void log(String msg) throws InterruptedException {
if(!shutdownRequested)
queue.put(msg);
else
throw new IllegalArgumentException("logger is shut down");
}

现在他这么说了

The implementation of log is chek-than-act sequnce: producers could observe that the service has not yet been shut down but still queue messages after the shutdown, again with the risk that the producer might get blocked in log and never become unlocked.

我不清楚强调的内容。

如果消费者将队列排空到某个集合,它将使 log() 中阻塞的任何生产者解锁。即使某些生产者尝试将日志消息放入队列,它也不会被阻止。我看到的唯一一件事是,由于队列已耗尽,因此不会记录此消息。

问题:为什么他说生产者可能会被阻止并且永远不会被解锁。我错过了什么?

最佳答案

如果您查看 BlockingQueue 文档,您可以看到:

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

即如果队列中没有更多空间,生产者可能会被阻塞:如果服务已关闭,则队列不会再被清空。

关于java - 了解关闭时的关闭请求标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36527479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com