Select in Squirrel

Our example demonstrates how to use Java’s ExecutorService and Future to simulate select-like behavior across multiple concurrent operations.

import java.util.concurrent.*;
import java.util.Arrays;
import java.util.List;

public class Select {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // We'll use Future for our example to simulate channel-like behavior
        Future<String> future1 = executor.submit(() -> {
            Thread.sleep(1000);
            return "one";
        });

        Future<String> future2 = executor.submit(() -> {
            Thread.sleep(2000);
            return "two";
        });

        List<Future<String>> futures = Arrays.asList(future1, future2);

        // We'll use CompletionService to await both of these values
        // simultaneously, printing each one as it arrives.
        CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
        futures.forEach(completionService::submit);

        for (int i = 0; i < 2; i++) {
            Future<String> completedFuture = completionService.take();
            String result = completedFuture.get();
            System.out.println("received " + result);
        }

        executor.shutdown();
    }
}

In this example, we use Java’s concurrency utilities to simulate the behavior of Go’s select statement:

  1. We create an ExecutorService to manage our concurrent tasks.

  2. We submit two tasks to the executor, each simulating a channel operation that completes after some time.

  3. We use a CompletionService to await the completion of these tasks. This allows us to process the results in the order they complete, similar to how select works in Go.

  4. We iterate twice, each time taking the next completed future and printing its result.

To run the program:

$ javac Select.java
$ java Select
received one
received two

Note that the total execution time is only about 2 seconds since both the 1 and 2 second sleeps execute concurrently.

While this Java code achieves similar functionality to the Go example, it’s worth noting that Java doesn’t have a direct equivalent to Go’s select statement. The CompletionService provides a way to handle multiple concurrent operations, but it doesn’t have the same level of language integration as Go’s select.