我需要双键并发哈希图。
我的第一次尝试只是使用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);
}
}
它是更好和完美的线程安全吗?(我不能决定所有方法都需要同步。)
还有其他推荐的方法吗?