6

The documentation of most collections in the Java standard library such as ConcurrentLinkedQueue, ConcurrentLinkedDequeue and ConcurrentSkipListSet come with the following disclaimer:

Beware that, unlike in most collections, the size method is not a constant-time operation. Because of the asynchronous nature of these sets, determining the current number of elements requires a traversal of the elements, and so may report inaccurate results if this collection is modified during traversal.

What does that mean? Why can't they keep a counter (say, an AtomicInteger) and just return the value on calls to size()?

Is it because the counter must be synchronized and therefore creates a choke point?

As a side note, ConcurrentHashMap does not seem to have this issue. Why is that? Looking at the source code, it seems like it uses multiple counters kept in an array that are summed on calls to size(). Is that to circumvent the choke point or is there another reason?

1
  • an atomic counter would definitely be bad.
    – ZhongYu
    May 19, 2015 at 19:26

1 Answer 1

6

Using a shared resource to maintain the size() would be both expensive and rather useless. size() is likely to be incorrect as soon as it returns as you cannot hold a lock on the collection so it can change between you calling it and when you get the value.

ConcurentHashMap has the same approach. The size() can be incorrect before the method has returned.

2
  • Of course size() can't be fully trusted, I accept that. But the problem I have is the non-constant cost of traversing every element in the collection to count them. But I guess I was right about the choke-point then? May 19, 2015 at 19:32
  • 1
    @GustavKarlsson Peter's first sentence really addresses the reason. Synchronization and cache invalidation would be very costly for a queue to operate. Yes, you were right, there would certainly be a bottle neck there. That is one of the main issues with ReentrantReadWriteLock
    – John Vint
    May 19, 2015 at 19:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.