【发布时间】:2013-08-20 20:17:39
【问题描述】:
我的代码如下,我得到 ConcurrentModificationException,特别是在 (String file : files) 行中
我在迭代时没有对“文件”进行任何更改,那么为什么会导致异常,我应该如何避免呢?感谢您的任何建议!
int getTotalLength(final HashSet<String> files) {
int total = 0;
int len;
for (String file : files) {
len = getLength(file);
if (len != Long.MIN_VALUE) {
total += len;
}
}
return total;
}
int getLength(String file) {
int len = Long.MIN_VALUE;
if (file == null) {
return len;
}
File f = new File(file);
if (f.exists() && f.isFile()) {
len = f.length();
}
return size;
}
【问题讨论】:
-
那么您是否有任何其他线程可能同时修改该集合?
-
是的,这是可能的,但我已将 hashSet 设置为最终...不会阻止集合被修改吗?
-
ConcurrentModification 在您的 HashSet 上,而不是在您的文件上
-
@GreenHo:不,你已经创建了 变量
final。这与变量值所引用的object是否可以修改无关。 -
@JonSkeet 这种混乱是我渴望在 Java 中使用
const的很大一部分原因,更不用说它会消除对 Guava 的Immutable*类的需求。 :-D
标签: multithreading hashmap hashset concurrentmodification