2012-01-27 36 views
-1

以下幾段代碼幾乎每次調用時都會引發ConcurrentModificationException。第二段代碼不會拋出異常,但它不是我需要的正確邏輯。如果對象是EditorFrame的實例,則需要調用自定義處置策略,這是close()方法的作用。但是,如果它只是一個基本框架,我希望它叫dispose()Java - ConcurrentModificationException

我環顧了這個網站,並按照一些說明,但沒有發現我的工作。

拋出異常的代碼:

synchronized (frameList) { 
    for (Iterator<JFrame> it = frameList.iterator(); it.hasNext();) { 
     JFrame frame = it.next(); 
     if (frame instanceof EditorFrame) ((EditorFrame) frame).close(); 
     else frame.dispose(); 
     it.remove(); 
    } 
} 

此代碼的工作,但它不是我想要的東西:

synchronized (frameList) { 
    for (Iterator<JFrame> it = frameList.iterator(); it.hasNext();) { 
     JFrame frame = it.next(); 
     frame.dispose(); 
     it.remove(); 
    } 
} 

感謝您的幫助!

+5

您是否在'EditorFrame.close'方法修改'frameList'? (當前線程將鎖定'frameList',鎖是可重入的,不應該需要鎖,因爲Swing只能用於事件調度線程(EDT)。) – 2012-01-27 00:19:22

+0

您可以發佈EditorFrame類嗎? – 2012-01-27 00:24:33

+0

同意Tom Hawtin:你應該只在單線程EDT上執行此代碼,所以不應該需要同步。哪條線通過這種方式拋出異常?此外,所有if/else塊,for循環,拍攝任何代碼塊都應該用大括號括起來以避免模糊。 – 2012-01-27 00:43:15

回答

6

沒有進入究竟是什麼導致ConcurrentModificationException。您仍在移除每個對象frameList

爲什麼在完成迭代列表後,您沒有明確地清除列表。

synchronized (frameList) { 
    for (JFrame frame : frameList) { 
     if (frame instanceof EditorFrame) ((EditorFrame) frame).close(); 
     else frame.dispose(); 
    } 
    frameList.clear(); 
} 
相關問題