Search code examples
javacollections

Java - ConcurrentLinkedQueue - poll all


Assume I have the class field of ConcurrentLinkedQueue type. Some methods of this class are offering the new elements to this queue. And some other methods need to poll for all the elements that are inside queue at this exact moment.

I can't use poll() in loop, because there is a chance that some elements might be offered to this queue while loop is still unfinished. And if the new elements are offered faster than I poll them, I think it can even be an endless loop. So I need some kind of pollAll().

Is there a way I can achieve this? Maybe there is a collection suitable for this?


Solution

  • If you can change your application to use one of the BlockingQueue implementations, there is a method drainTo that seems to do exactly what you want. It removes the current contents of the queue and transfers them to a destination collection.

    There are a variety of BlockingQueue implementations; they should all be thread-safe. Oddly, it's not specified that drainTo is atomic, though it is in the implementations I checked (ArrayBlockingQueue and LinkedBlockingQueue).