对于下面的函数,我尝试返回一个新集mHashSet,它是另一个集iGraphicSectors的副本。
public Set<String> getGraphics() {
synchronized (iGraphicSectors) { // class variable of type Set<String>
LinkedHashSet<String> mHashSet = new LinkedHashSet<String>();
synchronized (mHashSet) {
mHashSet.addAll(iGraphicSectors);
}
return mHashSet;
}
}但是,第5行mHashSet.addAll(iGraphicSectors);正在抛出一个ConcurrentModificationException (我不确定这是怎么可能的)。是否有办法以线程安全的方式完成上述任务?
发布于 2017-01-12 18:23:33
您需要做的是对Set使用线程安全的iGraphicSectors,因为您显然是同时读取和修改它,最简单的方法可以是使用装饰器Collections.synchronizedSet(Set s)使当前的Set线程安全,然后任何读和写访问都将通过synchronized块自动受到保护,这要归功于装饰器,但是您仍然需要使用synchronized块显式地保护对它的迭代。
下面是一个如何创建它的示例:
Set<String> iGraphicSectors = Collections.synchronizedSet(new HashSet<String>());下面是代码的外观:
public Set<String> getGraphics() {
// Still needed as the constructor of LinkedHashSet will iterate
// over iGraphicSectors
synchronized (iGraphicSectors) {
return new LinkedHashSet<String>(iGraphicSectors);
}
}发布于 2017-01-12 18:24:21
https://stackoverflow.com/questions/41619977
复制相似问题