Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AtomicLongMap vs. ConcurrentHashMultiset

From the documentation of AtomicLongMap:

Note: If your values are always positive and less than 2^31, you may wish to use a Multiset such as ConcurrentHashMultiset instead. Warning: Unlike Multiset, entries whose values are zero are not automatically removed from the map. Instead they must be removed manually with removeAllZeros().

It states that you may wish to use a Multiset. My question is, what are the benefits of a Multiset over an AtomicLongMap? What considerations should I use when choosing a map containing only positive values? Is the only reason to use a Multiset, the fact that I don't need to call removeAllZeros() manually?

like image 740
Benjy Kessler Avatar asked Sep 06 '25 03:09

Benjy Kessler


1 Answers

The Multiset is conceptually different. First, it's a Collection, so it can be used as collection, while AtomicLongMap is not a collection (and not a map either). The multiset represents a set of possibly repeating elements and to perform math operations with their counts, you add or remove elements. The AtomicLongMap method names more consistent with AtomicLong class and explicitly assume that you are performing math operations on the values. Some operations can be unsupported by one implementation or another. For example, there are addAndGet and getAndAdd ops in AtomicLongMap, but Multiset has only add method which works like getAndAdd.

So while in many cases these classes are interchangeable, use ConcurrentHashMultiset if you think of your data as of collection of possibly repeating elements. Use AtomicLongMap if you think of your data as of mapping between the key and the long value.

Note that since Java-8, these classes can be easily replaced with standard JDK ConcurrentHashMap<K, Long>. For example, you may use map.merge(key, 1L, Long::sum); to increment the mapped value.

like image 175
Tagir Valeev Avatar answered Sep 07 '25 22:09

Tagir Valeev