当我尝试将消息写入文件时出现 java.util.ConcurrentModificationException

标签 java

我是一名初级 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,并且可能会降低您的应用程序的响应速度。

关于当我尝试将消息写入文件时出现 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30285717/

相关文章:

java - Spring 匿名/回调类用于数据持久化的困难时期

java - ResultSetMetaData.getColumnName 为 UNION 和非 UNION 查询返回不同的值

java - 如何使用@Configuration配置Spring Webflow 2.3.1?

java - RequestMappingHandlerAdapter': Invocation of init method failed; nested exception is java. lang.NoSuchMethodError

java - Log4j - 根据项目模块记录到多个日志文件

java - Spring Cloud 与 Docker Swarm 和 Kubernetes 等编排工具的组合

java - 在 Oracle 中设置时间戳

java - ElasticSearch使字段无法从Java搜索

java - gradle 运行执行;已编译的 JAR 因 ClassNotFoundException 而崩溃

java - sessionFactory.getCurrentSession() 导致 NullPointerException