简体   繁体   中英

Atomically get Multiset entry in ConcurrentHashMultiset (guava)

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM