我是一名Java开发人员。我想用GUI编写电子邮件客户端,但是当我尝试运行WriteMessages线程时遇到问题。我正在使用JavaMail库。

public class WriteMessages implements Runnable {

    private List<Message> list;
    private Properties properties;
    private Utilities util = new Utilities();

    public WriteMessages(List<Message> list, Properties properties) {
        this.list = list;
        this.properties = properties;
    }

    @Override
    public void run() {

        Iterator<Message> iter = list.iterator();
        while (iter.hasNext()) {

            Message m = iter.next(); //line 42 exception occurs there

            String name = Morda.produceFileName(m);

            File file = new File(properties.getProperty("PathToMessages") + "//" + name);
            try {
                file.createNewFile();
            } catch (IOException ex) {
            }

            try (OutputStream os = new FileOutputStream(file);){
                m.writeTo(os);
                System.out.println("File " + file.getName() + " was wrote succesfuly");
            } catch (IOException | MessagingException ex) {
            }
        }
    }
}


我得到:

Message 0 added successfully.
Message 1 added successfully.
Message 2 added successfully.
Message 3 added successfully.
Thread is interrupted.
File 2011_07_17_08_55_27.mes was wrote succesfuly
Exception in thread "Thread-4" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
    at java.util.ArrayList$Itr.next(ArrayList.java:836)
    at util.WriteMessages.run(WriteMessages.java:42)
    at java.lang.Thread.run(Thread.java:745)


但是,当我删除此代码段时:

try (OutputStream os = new FileOutputStream(file);){
    m.writeTo(os);
    System.out.println("File " + file.getName() + " was wrote succesfuly");
} catch (IOException | MessagingException ex) {
}


没有出现异常。我认为这个问题已经解决,但是我找不到解决方法。请帮助我解决此问题。
谢谢。

最佳答案

在并发环境中,请考虑使用CopyOnWriteArrayList而不是简单的ArrayList。当您开始迭代它时,您将迭代迭代开始时的列表内容。通常这是期望的行为。使用Collections.synchronizedList实际上并不能帮助防止ConcurrentModificationException,并且可能会使您的应用程序响应速度降低。

08-03 21:23