[英]Iterate over collection in multithread environment: ConcurrentModificationException
I'm getting a ConcurrentModificationException
since this code is reached by several threads at the same time: 我收到一个ConcurrentModificationException
因为多个线程同时到达了此代码:
public void flush(Audit... audits) {
// Copy first them on memory
this.pendingAudits.addAll(Arrays.asList(audits));
for (Iterator<Audit> it = this.pendingAudits.iterator(); it.hasNext();) {
// Do something
it.remove();
}
}
I'm getting an iterator over pendingAudits
and I'm removing each element at the same time other threads can add some other audits. 我正在获得一个pendingAudits
的迭代器迭代器,并且在其他线程可以添加其他审计的同时删除每个元素。
How to solve it elegantly? 如何优雅地解决它?
A quick solution is to wrap every access to this.pendingAudits
in synchronized
: 一个快速的解决办法是换每次访问this.pendingAudits
在synchronized
:
sychronized(this.pendingAudits) {
this.pendingAudits.addAll(Arrays.asList(audits));
for (Iterator<Audit> it = this.pendingAudits.iterator(); it.hasNext();) {
// Do something
it.remove();
}
}
The net effect will be that at any given time only one thread can be executing the synchronized block. 最终结果是,在任何给定时间,只有一个线程可以执行同步块。 That can become a bottleneck if the code is executed frequently. 如果频繁执行代码,则可能成为瓶颈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.