Ras*_*ran 4 java concurrenthashmap data-structures
我需要有键值对,其中值可以是一组。此数据结构应该是线程安全的,以便在多线程环境中将删除元素添加到集合中。
我的要求是创建一个订阅列表,在这里人们可以订阅不同的主题。这个订阅列表应该是并发的、线程安全的、快速的。我正在考虑使用 ConcurentHashMap 和 ConcurrentHashSet,这对我没有帮助,因为我必须将同步块放在顶层,它将阻塞整个映射,直到放置/删除操作完成。
没有预先滚动的解决方案,但可以使用具有ConcurrentMap<K, Set<V>>使用usingSet<V>生成的值的来实现简单值的线程安全并发。ConcurrentMap<V, Boolean>Collections.newSetFromMap(Map<V,Boolean>)
然后,要以原子方式获取每个值集,请使用ConcurrentMap.computeIfAbsent(K, Function<? super K, ? extends Set<V>>):
ConcurrentMap<String, Set<Integer>> multimap = new ConcurrentHashMap<>();
Set<Integer> fooValues = multimap.computeIfAbsent("foo", key -> Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>()));
Run Code Online (Sandbox Code Playgroud)
如果您希望值具有稳定的迭代顺序,则可以使用 aConcurrentSkipListSet来保存值:
ConcurrentMap<String, NavigableSet<Integer>> multimap = new ConcurrentHashMap<>();
NavigableSet<Integer> fooValues = multimap.computeIfAbsent("foo", key -> new ConcurrentSkipListSet<>());
Run Code Online (Sandbox Code Playgroud)
同样,为了Set<V>以线程安全的方式删除值持有者实例,您可以使用ConcurrentMap.computeIfPresent(K, BiFunction<? super K,? super Set<V>,? extends 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;
});
}
Run Code Online (Sandbox Code Playgroud)
请注意,Java 核心库没有提供“ConcurrentHashSet ”类。
| 归档时间: |
|
| 查看次数: |
3353 次 |
| 最近记录: |