gpt4 book ai didi

Java 与集合的并发

转载 作者:行者123 更新时间:2023-11-30 06:56:56 25 4
gpt4 key购买 nike

对于下面的函数,我试图返回一个新的集合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 (我不确定这是怎么可能的)。有没有办法以线程安全的方式完成上述任务?

最佳答案

您需要做的是使用 Set对于 iGraphicSectors 来说是线程安全的因为您显然同时读取和修改它,最简单的方法是使用装饰器 Collections.synchronizedSet(Set<T> s) 使您当前的Set线程安全,任何读写访问都将自动受到 synchronized 的保护。由于装饰器的作用而阻止,但是您仍然需要使用 synchronized 显式保护它的迭代。 block 。

以下是如何创建它的示例:

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);
}
}

关于Java 与集合的并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41619977/

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