gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:52:09 24 4
gpt4 key购买 nike

我是一名初级 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com