java - LinkedList 中的无限循环(并发问题?)
问题描述
在极少数情况下,下面的代码会在打印“entry is null!”的无限循环中运行。但该条目不应该为空!我无法重现它,但它时常发生。这怎么可能?!?如果有帮助,代码由 REST 端点触发,这意味着可以有多个线程调用此代码。但是,我仍然不明白这怎么会导致无限循环?!我错过了什么?
private final Queue<Event> queue = new LinkedList<>();
void addToQueue(String data) {
// only place elements are added to the queue
this.queue.offer(new Event(data));
}
public void doStuff() {
while (!queue.isEmpty()) {
var entry = queue.poll();
if (entry == null) {
System.out.println("entry is null!"); // HOW CAN THIS LOOP INFINITELY?
} else {
// do sth. useful with entry
// additional entries can be added to the queue here with `addToQueue()`
}
}
}
static class Event {
final String data;
Event(String data) { this.data = data; }
}
只有 1 个地方将新元素添加到队列中,并且该方法确保不能将空值添加到队列中。
编辑:删除synchronized
,因为它与问题无关。
解决方案
推荐阅读
- python - 如何在 python 中绘制移动平均线?
- google-api-js-client - 从 Google Photos API 生成的视频缩略图中删除“播放”符号
- vb.net - 从浏览器中提取 cookie 并附加到 WebRequest
- python-3.x - 为什么嵌入维度必须被MultiheadAttention中的头数整除?
- amazon-web-services - AWS SageMaker 笔记本扩展安装
- spring - Spring Boot Batch:分页在 DB2 数据源中似乎没有按预期工作
- sql - SQL 按行号顺序连接字符串
- javascript - 当值未定义(不使用#if)时,如何摆脱handlebars.js中的额外空间?
- html - 如何将 p 标签与中心标签的左侧对齐?
- git - 如何在子模块树中添加自定义文件夹