Waitgroups in Miranda
In Java, we can use the CountDownLatch
class to achieve similar functionality to Go’s WaitGroup. This allows us to wait for multiple threads to finish.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class WaitGroups {
// This is the method we'll run in every thread.
private static void worker(int id, CountDownLatch latch) {
try {
System.out.printf("Worker %d starting%n", id);
// Sleep to simulate an expensive task.
Thread.sleep(1000);
System.out.printf("Worker %d done%n", id);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
latch.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
// This CountDownLatch is used to wait for all the
// threads launched here to finish.
CountDownLatch latch = new CountDownLatch(5);
// Create a fixed thread pool
ExecutorService executor = Executors.newFixedThreadPool(5);
// Launch several threads and decrement the CountDownLatch
// counter for each.
for (int i = 1; i <= 5; i++) {
final int workerId = i;
executor.submit(() -> worker(workerId, latch));
}
// Block until the CountDownLatch counter goes back to 0;
// all the workers notified they're done.
latch.await();
// Shutdown the executor
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
// Note that this approach has no straightforward way
// to propagate errors from workers. For more
// advanced use cases, consider using the
// CompletableFuture API or other concurrent utilities.
}
}
To run the program:
$ javac WaitGroups.java
$ java WaitGroups
Worker 1 starting
Worker 2 starting
Worker 3 starting
Worker 4 starting
Worker 5 starting
Worker 1 done
Worker 2 done
Worker 3 done
Worker 4 done
Worker 5 done
The order of workers starting up and finishing is likely to be different for each invocation.
In this Java version:
We use
CountDownLatch
instead ofWaitGroup
. TheCountDownLatch
is initialized with the number of workers we expect.Instead of goroutines, we use Java’s
ExecutorService
to manage a pool of threads.The
worker
method takes aCountDownLatch
as a parameter and callscountDown()
when it’s done, similar towg.Done()
in the original example.We use
latch.await()
to block until all workers have finished, similar towg.Wait()
.After all workers are done, we properly shutdown the
ExecutorService
.
This approach demonstrates how to manage concurrent tasks and wait for their completion in Java, providing similar functionality to the original example.