简体   繁体   中英

size of ConcurrentLinkedQueue

Reading Java's ConcurrentLinkedQueue Docs , I wonder why it is not possible for the implementation to store the size:

Beware that, unlike in most collections, the size method is NOT a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires a traversal of the elements.

Where in the source is this "asynchronous nature"? I only see a while-loop to retry enqueing until the AtomicReferences match the expected values/references. Why is it not possible to increment an size:AtomicInteger after successfully offering a value to the Queue?

Thanks alot.

Imagine you have two threads, one adding a new item, and the other deleting an item. There are no items in the queue at the start.

Suppose the first thread adds the item, immediately followed by the other thread removing the item and decrementing the size, at which point your size is at -1, then the first thread increments the size to 0.

A slightly contrived example, but you would need to make the whole operation atomic in order to ensure that no other threads could get access to the size of -1.

One of the important performance benefit of ConcurrentLinkedQueue comes from the fact that you don't worry about the tail when you update the head, and vice versa, right?

This means basically that 2 threads can poll/offer at the same time without interfering (if the queue size wasn't 0, that is).

This weren't the case if you had a counter. Even if it was a AtomicInteger which has good concurrency, you will still have increased possibility of having failed CAS operations because now you have this "hot spot" that you update every time you do poll/offer.

Not entirely sure if the authors mean this when they say "asynchronous nature", but I think this is the biggest reason they don't have a counter like you suggested.

Why is it not possible to increment an size:AtomicInteger after successfully offering a value to the Queue?

Probably because that offer/decrement could not be done atomically without adversely affecting the concurrency of the method.

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