关于 java 中的双键并发哈希映射

About dual key concurrent hashmap in java

我需要双键并发哈希映射。

我的第一次尝试只是使用 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);
    }
}

它是不是更好而且完全线程安全? (我无法决定所有方法都需要 synchronized。)

还有其他推荐的方法吗?

All options are thread-safe, which is guaranteed by ConcurrentHashMap. Important 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 使用的实例比需要的多得多。