有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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; }
}

只有一个地方可以向队列中添加新元素,并且该方法确保不能向队列中添加空值

编辑:删除synchronized,因为它与问题无关


共 (0) 个答案