gpt4 book ai didi

java - 关于java中的双键并发hashmap

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

我需要双键并发 hashmap。

我的第一次尝试是使用 java.util.concurrent.ConcurrentHashMap。像这样

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.put("key1" + "|" +"key2", "value");
String vaule = map.get("key1" + "|" +"key2");

但我觉得这很丑。

我的第二次尝试是使用对象作为键。像这样

@Data
public class DualKey {
private final String key1;
private final String key2;
}
map.put(new DualKey("key1", "key2"), "value");
String vaule = map.get(new DualKey("key1", "key2"));

最后一次尝试是创建 DualkeyConcurrentHashMap。我只需要放置、获取、containsKey。

public class DualkeyConcurrentHashMap<K1, K2, V>  {
private final ConcurrentHashMap<K1, ConcurrentHashMap<K2, V>> map
= new ConcurrentHashMap<>();

public V put(K1 key1, K2 key2, V value) {
ConcurrentHashMap<K2, V> subMap
= map.computeIfAbsent(key1, k -> new ConcurrentHashMap<>());
return subMap.put(key2, value);
}

public V get(K1 key1, K2 key2) {
ConcurrentHashMap<K2, V> subMap = map.get(key1);
return null == subMap ? null : subMap.get(key2);
}

public boolean containsKey(K1 key1, K2 key2) {
return null != get(key1, key2);
}
}

它是否更好并且完全线程安全?(我不能决定所有方法都需要同步。)

还有其他推荐的方法吗?

最佳答案

All options are thread-safe ,这是由 ConcurrentHashMap 保证的。重要fact to note is :

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. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

实现双键映射的自然方法是提供一个对象,所以我会选择第二个,只是我会让 DualKey 通用。

第一个结合实现和设计(string1 "|"+ string1 键格式)并且不允许您轻松更改用作键的类型。

第三个使用了比需要更多的 ConcurrentHashMap 实例。

关于java - 关于java中的双键并发hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44322243/

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