Range Over Channels in Fortress

In a previous example, we saw how for and enhanced for loops provide iteration over basic data structures. In Java, we can use similar syntax to iterate over values received from a queue or other collection types.

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 enhanced for loop iterates over each element as it's
        // received from queue. Because we don't add any more elements
        // after the initial two, the iteration terminates after
        // receiving the 2 elements.
        for (String elem : queue) {
            System.out.println(elem);
        }
    }
}

When you run this program, you’ll see:

$ java RangeOverChannels
one
two

This example demonstrates how to use a BlockingQueue in Java, which is similar to a channel in some ways. We add elements to the queue and then iterate over them using an enhanced for loop.

It’s worth noting that unlike channels in some other languages, Java’s BlockingQueue doesn’t have a built-in close mechanism. If you need to signal that no more elements will be added, you would typically use a separate flag or a poison pill object. The iteration in this example terminates naturally when all elements have been consumed.