Range Over Channels in Java

In a previous example, we saw how for loops provide iteration over basic data structures. In Java, we can use similar concepts to iterate over values received from a queue.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class RangeOverChannels {
    public static void main(String[] args) throws InterruptedException {
        // We'll iterate over 2 values in the queue
        BlockingQueue<String> queue = new LinkedBlockingQueue<>(2);
        queue.put("one");
        queue.put("two");

        // This loop iterates over each element as it's received from queue.
        // Because we used a fixed-size queue and added all elements,
        // the iteration will terminate after receiving the 2 elements.
        while (!queue.isEmpty()) {
            String elem = queue.take();
            System.out.println(elem);
        }
    }
}

When you run this program, you’ll see:

$ javac RangeOverChannels.java
$ java RangeOverChannels
one
two

This example demonstrates how to use a BlockingQueue in Java, which is similar to a channel in other languages. We add elements to the queue and then iterate over them until the queue is empty.

In Java, we don’t have a direct equivalent to the range keyword for iterating over channels. Instead, we use a while loop to check if the queue is empty and the take() method to retrieve elements.

This approach also shows that it’s possible to add elements to a queue and still have the remaining values be received, even after no more elements are being added. The take() method will block if the queue is empty, but in this case, it won’t block because we’ve added all elements before starting to consume them.