首页 > 解决方案 > 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,因为它与问题无关。

标签: javarestconcurrencylinked-listqueue

解决方案


推荐阅读