Range Over Channels in Groovy

Our example demonstrates how to iterate over values received from a channel in Groovy. While Groovy doesn’t have built-in channels like some other languages, we can simulate this behavior using a BlockingQueue.

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

// We'll iterate over 2 values in the `queue`.
def queue = new LinkedBlockingQueue<String>(2)
queue.put("one")
queue.put("two")

// This loop iterates over each element as it's received from `queue`.
// Because we used a queue with a fixed capacity, the iteration terminates
// after receiving the 2 elements.
queue.each { elem ->
    println elem
}

When you run this script, you’ll see:

one
two

This example shows how to iterate over elements in a queue, which is similar to ranging over a channel in some other languages. In Groovy, we use a BlockingQueue to simulate channel-like behavior.

The each method in Groovy provides functionality similar to ranging over a channel. It iterates over each element in the queue, processing them one by one.

Note that unlike channels in some other languages, a BlockingQueue in Groovy/Java doesn’t have a built-in close method. The iteration naturally terminates when all elements have been processed. If you need to signal that no more elements will be added, you might need to implement additional logic or use a different concurrent structure depending on your specific requirements.

This example also demonstrates how to work with fixed-capacity queues and process all elements in them, which is conceptually similar to closing a non-empty channel and still receiving the remaining values in some other languages.