并发很难。如果您要为并发映射而不是直接锁定而烦恼,则不妨这样做。确实,不要进行不必要的查找。
Set<X> set = map.get(name);if (set == null) { final Set<X> value = new HashSet<X>(); set = map.putIfAbsent(name, value); if (set == null) { set = value; }}(通常的stackoverflow免责声明:超出我的头脑。未经测试。未经编译。等等。)
更新:
1.8已向中添加了
computeIfAbsent默认方法
ConcurrentMap(
Map这很有趣,因为该实现对错误
ConcurrentMap)。(并且1.7添加了“钻石算子”
<>。)
Set<X> set = map.computeIfAbsent(name, n -> new HashSet<>());
(请注意,您应对
HashSet。中包含的的任何操作的线程安全负责
ConcurrentMap。)



