gpt4 book ai didi

java - BlockingQueue 在调用之前不处理中断

转载 作者:行者123 更新时间:2023-12-01 23:17:36 26 4
gpt4 key购买 nike

我正在使用 RabbitMQ,它默认为消费者使用 LinkedBlockingQueue 。它有一个阻塞的 nextDelivery() 方法,该方法基本上调用队列上的 take()

但是如果在调用该方法之前被中断,它不会捕获中断。

if (Thread.interrupted()) {
throw new InterruptedException();
}
// If interrupted here, call below will not throw interrupted exception
rabbit.nextDelivery();

只有在等待时中断命中(这也是 javadoc 中所写的)或者先命中 if block 时它才起作用。

Throws:
InterruptedException - if interrupted while waiting

实际上,我遇到过这样的情况:中断正好发生在我标记的地方。如果我在开始时或中间设置 sleep ,它会起作用,但仍然不能安全地假设它总是有效。

是否有替代的 BlockingQueue 实现可以解决此问题?我不知道是否中断它消耗了,也许静态方法中存在竞争条件它返回 false 但以某种方式清除设置值?

编辑:这与Thread.interrupted()调用或不设置标志无关。如果你注释掉 if block ,又是同样的问题。 Queue 方法一进入就不会抛出 InterruptedException,它只是阻塞

最佳答案

But it doesn't catch the interrupt if it was interrupted just before calling that method.

所以,如果我理解你的问题,那么某些东西正在吞噬 InterruptedException 或清除中断标志。下面的代码总是抛出 InterruptedException

Thread.currentThread().interrupt();
new LinkedBlockingQueue<String>().take();

重要的是要认识到,当抛出InterruptException时,中断标志将被清除。您应该始终执行以下操作:

try {
// other methods where this is needed are Object.wait(...), Thread.join(...)
Thread.sleep(100);
} catch (InterruptedException ie) {
// re-interrupt the thread
Thread.currentThread().interrupt();
// deal with the interrupt by returning or something
...
}

参见:Why invoke Thread.currentThread.interrupt() when catch any InterruptException?

经常发生的情况是,由于代码错误,第 3 方代码不会传播中断状态。那么你通常会遇到 SOL,因为中断将被吞掉并且 take() 方法不会抛出异常。

此外,重要的是要认识到 Thread.interrupted() 清除中断标志。通常您需要使用 Thread.currentThread().isInterrupted() 来测试中断标志的状态。

Is there an alternative BlockingQueue implementation addresses this issue?

我不确定是否存在问题。

关于java - BlockingQueue 在调用之前不处理中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20983570/

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