Are there concurrency multivalued HashMap data structures in Java?
I have a requirement for key-value pairs where the values can be a collection. This data structure should be thread-safe to add and remove elements to the collection in a multithreaded environment.
My request is to create a subscription list where people can subscribe to different topics. This subscription list should be concurrent, thread-safe, and fast. I’m thinking about using ConcurentHashMap and ConcurrentHashSet, which doesn’t help me because I have to put the synchronized block on top and it blocks the entire map until the put/delete operation is complete.
Solution
There is no pre-rolling solution, but thread-safe concurrency can be achieved using ConcurrentMap<K, Set<V>>
for simple values. Among them are Set
<V> values made by ConcurrentMap<V, Boolean>
Collections.newSetFromMap (Map<V, Boolean>).
.
Then, to get each set of values atomically, use 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>()));
If you want your values to have a stable iteration order, you can use ConcurrentSkipListSet
Save value instead:
ConcurrentMap<String, NavigableSet<Integer>> multimap = new ConcurrentHashMap<>();
NavigableSet<Integer> fooValues = multimap.computeIfAbsent("foo", key -> new ConcurrentSkipListSet<>());
Similarly, in
order to remove the Set<V>
value holder instance in a thread-safe manner, you can use <a href=” https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentMap.html#computeIfPresent-K-java.util.function.BiFunction-” rel=”noreferrer noopener nofollow”> 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;
});
}
Note there is no ” ConcurrentHashSet
” class provided by the Java core libraries .