gpt4 book ai didi

java - 关于 LinkedBlockingQueue 迭代器从不抛出 ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-05 07:40:12 25 4
gpt4 key购买 nike

java.util.concurrent.ThreadPoolExecutor 有以下方法:

public void purge() {
final BlockingQueue<Runnable> q = workQueue;
try {
Iterator<Runnable> it = q.iterator();
while (it.hasNext()) {
Runnable r = it.next();
if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
it.remove();
}
} catch (ConcurrentModificationException fallThrough) {
// Take slow path if we encounter interference during traversal.
// Make copy for traversal and call remove for cancelled entries.
// The slow path is more likely to be O(N*N).
for (Object r : q.toArray())
if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
q.remove(r);
}

tryTerminate(); // In case SHUTDOWN and now empty
}

有一个异常ConcurrentModificationException,但是在Java doc中我可以看到:

The returned iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

请告诉我如何理解。

最佳答案

正如您在 ThreadPoolExecutor 构造函数中所见,您可以为其提供任何 BlockingQueue

public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)

它可以是您自己的实现,它不必是弱一致的,尽管它不必抛出 ConcurrentModificationException 要么这是抛出的常见异常,因此这是一些防御性编程Java 开发人员。

关于java - 关于 LinkedBlockingQueue 迭代器从不抛出 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46377086/

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