关于LinkedBlockingQueue迭代器从不抛出ConcurrentModificationException异常

3

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
}

在Java文档中,我看到有一个“ConcurrentModificationException”异常,但是文档中同时指出:返回的迭代器是“弱一致性”迭代器,在遍历元素时绝不会抛出ConcurrentModificationException异常,并保证按照迭代器构造时元素的存在顺序来遍历元素,并且可能(但不能保证)反映构造后的任何修改。请告诉我如何理解。

你引用的Java文档是来自哪个类或方法? - Naman
ref LinkedBlockingQueue - FeidD
你可以搜索一下 Iterator 方法;在这里有链接 https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html - FeidD
请参考 https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html 并验证该类中未使用 LinkedBlockingQueue。 - Naman
1个回答

0

正如您在ThreadPoolExecutor构造函数中所看到的,您可以向其提供任何BlockingQueue

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

它可以是你自己的实现,不必弱一致性,尽管它也不必抛出ConcurrentModificationException,但这通常是Java开发人员使用的防御性编程所抛出的异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接