2017-09-23 56 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

相關問題