Select in Miranda
Our example demonstrates how to use Java’s concurrency features to wait on multiple operations simultaneously. We’ll use threads and an ExecutorService
to simulate concurrent operations, and a CompletableFuture
to handle the results.
In this example, we use CompletableFuture
to simulate channels. Each CompletableFuture
will complete after some amount of time, simulating blocking operations executing in concurrent threads.
We use CompletableFuture.anyOf
to await both of these values simultaneously, printing each one as it arrives.
To run the program:
Note that the total execution time is only ~2 seconds since both the 1 and 2 second sleeps execute concurrently.
This Java implementation uses different concurrency constructs than the original example, but it achieves a similar effect. The ExecutorService
manages our threads, CompletableFuture
represents our asynchronous operations, and CompletableFuture.anyOf
serves a similar purpose to the select
statement in the original code.