关于LinkedBlockingQueue迭代器永远不会抛出ConcurrentModificationException

时间:2017-09-23 07:17:02

标签: 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文档中,我可以看到:

  

返回的迭代器是一个&#34;弱一致的&#34;永远不会抛出ConcurrentModificationException的迭代器,并保证在构造迭代器时遍历元素,并且可能(但不保证)反映构造之后的任何修改。

请告诉我如何理解。

1 个答案:

答案 0 :(得分:0)

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

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

它可以是你自己的实现,它不必是弱一致的,虽然它不必抛出ConcurrentModificationException这也是抛出的常见异常,这是Java开发人员的一些防御性编程。