Question

Suppose I have an instance of LinkedBlockingQueue queue; and want to use for each with this queue:

for(Object obj : queue)  {

//do smth
}

How will this code behave in case if queue is empty at the moment? Will it block the running until queue will become not empty or not?

Thanks!

Was it helpful?

Solution

It does not block, it simply does not enter in the loop branch.

You can easily check:

LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
for (Object obj : queue) {
    System.out.println("Inside the loop, is empty? " + queue.isEmpty());
}
System.out.println("Not blocking, is empty? " + queue.isEmpty());

Output: Not blocking, is empty? true

OTHER TIPS

No, it would not block (demo).

Java's for-each loop gets the iterator from the collection, and uses that iterator to traverse the collection. According to the documentation, the iterator of LinkedBlockingQueue<T> collection reflects the state of the queue at the time the iterator is constructed:

The returned iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator.

Since the queue is empty at the time the iterator is constructed, the iterator would not wait for more data to become available, and report that it has no additional elements. Of course, if the collection becomes non-empty after the construction of the iterator, the iterator may return some of the newly inserted items.

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