在Java中是否有任何Concurrent多值HashMap数据结构?

时间:2017-10-27 05:20:59

标签: java data-structures concurrenthashmap

我需要具有键值对,其中值可以是一组。此数据结构应该是线程安全的,以便在多线程环境中将删除元素添加到集合中 我的要求是创建一个订阅列表,这里人们可以订阅不同的主题。此订阅列表应该是并发的,线程安全且快速的。我正在考虑使用ConcurentHashMap和ConcurrentHashSet,这对我没有帮助,因为我必须将同步块放在顶层,它将阻塞整个映射,直到put / remove操作完成。

2 个答案:

答案 0 :(得分:1)

没有预先推出的解决方案,但可以使用ConcurrentMap<K, Set<V>> Set<V>使用ConcurrentMap<V, Boolean>使用ConcurrentMap<String, Set<Integer>> multimap = new ConcurrentHashMap<>(); Set<Integer> fooValues = multimap.computeIfAbsent("foo", key -> Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>())); 来实现简单值的线程安全并发性}}

然后,要以原子方式设置每个值,请使用Collections.newSetFromMap(Map<V,Boolean>)

ConcurrentMap<String, NavigableSet<Integer>> multimap = new ConcurrentHashMap<>();
NavigableSet<Integer> fooValues = multimap.computeIfAbsent("foo", key -> new ConcurrentSkipListSet<>());

如果您希望您的值具有稳定的迭代顺序,则可以使用ConcurrentMap.computeIfAbsent(K, Function<? super K, ? extends Set<V>>)来保存值:

Set<V>

同样,为了以线程安全的方式删除public static <K, V> void remove(final ConcurrentMap<K, Collection<? extends V>> multimap, final K key, final V value) { multimap.computeIfPresent(key, (k, oldValues) -> { final Collection<? extends V> newValues; if (oldValues.remove(value) && oldValues.isEmpty()) { // Remove the empty set from the multimap newValues = null; } else { newValues = oldValues; } return newValues; }); } 值持有者实例,您可以使用ConcurrentSkipListSet

CollectionViewSource

请注意ConcurrentMap.computeIfPresent(K, BiFunction<? super K,? super Set<V>,? extends Set<V>>)

答案 1 :(得分:-1)

你写的&#34;价值可以是一套&#34;但不要提到密钥是什么。在任何情况下,Hashtable是Java中存在的第一个映射,它是线程安全的,可以添加/删除/替换键,值对。

您可以使用here中描述的方法之一创建线程安全的Set。该集合是否作为值存储在散列映射中没有任何区别。

相关问题