Question

Wondering why the method drainTo is present only in the concurrent collection framework (BlockingQueue in particular) and not in the regular one. Is there any reason for that? Thanks in advance.

Was it helpful?

Solution

As always with that sort of question it is difficult to say without asking the author of the class himself. But we can make some educated guesses.

The javadoc states:

Removes all available elements from this queue and adds them to the given collection. This operation may be more efficient than repeatedly polling this queue.

So the underlying reason is probably for efficiency.

drainTo is essentially equivalent (in a single threaded environment, for simplicity) to:

while ((e = queue.poll()) != null) collection.add(e);

With a blocking queue, each iteration is (most likely) going to acquire some lock and release it again, which is not optimal. If you look at the implementation in ArrayBlockingQueue for example, you will see that the lock is acquired once for the whole iteration, probably because the authors of the library found that it was more efficient.

OTHER TIPS

The point is here that all locking and signalling happens outside of the pseudocoded while block, so yes, it is for efficiency only. For non-concurrent queues, there is no such protection anyway, so the while-block would be enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top