Reputation: 89
I have a ConcurrentHashMultiset
and I'd like to atomically retrieve the count of an element and the total size of the multiset. Something like
final double count = set.count(element);
final double size = set.size();
but as an atomic operation. Is there any way to do that without using read/write mutexes for all usages of the set or creating an immutable copy of the set?
Upvotes: 0
Views: 359
Reputation: 16516
If you look into an implementation of ConcurrentHashMultiset
:
private final transient ConcurrentMap<E, AtomicInteger> countMap;
There is no non-blocking way to get atomically two values out of this. These are two separate operations.
toArray()
is non-atomic for this operation as it non-blockingly relies on iterating over a list of AtomicInteger
s which may change in time.
Upvotes: 3
Reputation: 24454
Use toArray
to get a copy of it! Everything else makes no sense. Even if were possible to get the size and the count atomically, you could never be sure that the set isn't modified by another thread right after that.
Apart from that: Size isn't guaranteed to return an exact value! If another threads modify the set while size
is called, it is undefined weather or not these modifications affects the size calculation.
Upvotes: 3