【发布时间】:2020-10-24 05:09:00
【问题描述】:
有一个生产者不断生成文件并将它们放入一个特殊的路径。消费者是使用WatchService 来监视路径并选择任何新生成的文件来工作。通常,消费者的速度比生产者慢。在极少数情况下,如果消费者完成了所有现有任务并且路径中还没有新内容,消费者需要坚持一段时间。
while(true) {
// do something...
if(condition) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// handler
}
}
}
IDE 抱怨 calling to Thread.sleep() in a while loop are indicative of "busy-waiting". Busy-waiting is often inefficient, and may result in unexpected deadlocks as busy-waiting threads do not release locked resources。忽略此 IDE 警告将是我的最后选择。
如何更改我的代码以避免上述警告架构明智?
(调度的线程池好像不能满足我的要求,如有错误请指正。)
感谢您的 cmets 和回答。从 WatchService 缓冲事件到阻塞队列将起作用。
【问题讨论】:
-
这是 IDE 警告,而不是编译器警告。忽略它。
-
要么忽略它,要么使用调度器
-
那个有点看起来像Semaphore(如果你从远处看它并眯起眼睛),除了它会等待预定的时间。
-
我睡不着。在这里查看我的答案stackoverflow.com/questions/62293246/…,看看你是否可以使用类似的东西。
-
使用WatchService 检测文件系统事件并将这些事件排队到BlockingQueue 实现中,例如足够大小的ArrayBlockingQueue。
标签: java multithreading performance deadlock