2017-09-23 73 views
2

java.util.concurrent.ThreadPoolExecutor有以下方法:关于的LinkedBlockingQueue迭代器不会抛出ConcurrentModificationException

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

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

请告诉我如何理解。

+0

您引用的java文档是来自哪个类或方法? – nullpointer

+0

ref LinkedBlockingQueue – FeidD

+0

您可以搜索关于方法迭代器; https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html – FeidD

回答

0

正如你可以在ThreadPoolExecutor构造看,你可以用任何BlockingQueue

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

提供它可以自己实现它不必是弱一致的,虽然它没有丢ConcurrentModificationException这是通常抛出的异常,所以这是Java开发人员的一些防御性编程。

+0

谢谢,你的权利:) – FeidD

相关问题