Reputation: 7656
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?
Upvotes: 4
Views: 1363
Reputation: 100269
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.
Upvotes: 4