【发布时间】:2017-07-29 11:23:25
【问题描述】:
我使用 ConcurrentHashMap 和 TreeSet 作为值。此哈希映射由多个线程共享。
当一个线程接收到客户端对某个键的请求时,它会检查该键是否存在于 hashmap 中,如果存在,它将新请求作为 MyClass 对象添加到相应的TreeSet 中。否则创建一个新的TreeSet 并使用该键插入HashMap。
代码sn-p:
public static ConcurrentHashMap<String, TreeSet<MyClass>> messageMap =
new ConcurrentHashMap<String, TreeSet<MyClass>>();
TreeSet<MyClass> treeSM = new TreeSet<MyClass>();
if (messageMap.containsKey(key)) {
treeSM = messageMap.get(key);
}
treeSM.add(sm);
messageMap.put(key, treeSM);
如果两个线程同时收到对相同键的请求,则映射包含不一致的值。两个线程都将messageMap.containsKey(key) 的结果设为false,并将新构建的TreeSet 对象作为键值。所以最终那个键的 TreeSet 只有一个 MyClass 对象而不是两个。
【问题讨论】:
标签: multithreading synchronization java-7 concurrenthashmap