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

标签 java concurrency

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/

相关文章:

java - NullPointerException,集合不存储数据?

java - JMS 1.1 : Load sharing client side for Point-to-Point mode

C# 通过引用互斥

c# - 在文件系统级别同步写入文件

java - LinkedBlockingQueue 抛出 InterruptedException

java - 基于物联网的家庭自动化系统(如 Alexa)中使用的设计模式

java - 配置 Java AWS Lambda 使用的 Objectmapper

java - 使用 Objectify 将父项/子项批量存储到 Appengine 上

java - 使用 Spring Security @configuration 的同一应用程序中的两个领域

concurrency - Erlang的rpc的区别:multicall/4 vs rpc:pmap/3