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

标签 java multithreading concurrency concurrenthashmap multikey

我需要双键并发 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。我只需要 put、get、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/

相关文章:

java - 如何为 jackson 启用严格类型解析?

java - 刷新 header 后,在 Java 中的响应中添加 cookie?

java - 在java中同步大量线程的最佳方法

php - 原则 2 并发问题

java - 在java中自动更正输入的字符串值

java - 等待 JavaFX 应用程序线程完成事件处理?

c++ - 多线程任务整体进度报告设计模式

c# - 使用 DateTime.Now.Ticks 生成唯一的数字 ID

concurrency - 是否可以只允许一个线程改变共享数据?

Java二进制转换器