简体   繁体   中英

Java - ConcurrentModificationException

The following piece of code throws a ConcurrentModificationException almost every time it is called. The second piece of code does not throw the exception, however it is not the correct logic that I need. If the object is an instance of EditorFrame , I need to invoke a custom disposal strategy which is what the close() method is. However if it is just a basic frame I want it to call dispose() .

I've looked around this site and followed some instructions, but none that I found have worked.

The code that throws the exception:

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();
    }
}

This code works, but it's not what I want:

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

Thanks for helping!

Without getting in to exactly what is causing the ConcurrentModificationException. you are still removing every object from frameList

why don't you clear the list explicitly after you finished iterating the list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM