gpt4 book ai didi

java - 我的集合在 ConcurrentMap 中是线程安全的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:53:04 24 4
gpt4 key购买 nike

我有以下代码。即使集合本身不是线程安全的,它也会是线程安全的吗?

private ConcurrentMap<REGISTRY, Set<CONTACT_ROLES>> proxyRoles = new ConcurrentHashMap<REGISTRY, Set<CONTACT_ROLES>>(); 


public void setProxyRoles(ConcurrentMap<REGISTRY, Set<CONTACT_ROLES>> proxyRoles) {
this.proxyRoles = proxyRoles;
}

public ConcurrentMap<REGISTRY, Set<CONTACT_ROLES>> getProxyRoles() {
return proxyRoles;
}

public synchronized void addProxyRole(REGISTRY reg, CONTACT_ROLES role) {
if(proxyRoles.get(reg) == null){
proxyRoles.put(reg, new HashSet<CONTACT_ROLES>());
}
proxyRoles.get(reg).add(role);

}

编辑:

在一些非常好的答案之后,我明白我的解决方案是不安全的,我用谷歌搜索了一下,在 ConcurrentSkipListSet 中找到了一个很好的替代方案

最佳答案

来自 Javadoc:

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access.

因此,如果 2 个线程同时访问该集合,它们将不会获取整个集合的锁。

关于java - 我的集合在 ConcurrentMap 中是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9313382/

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