Search code examples
javamultithreadingjava.util.concurrentblockingqueue

for each in blocking collection


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!


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