Waitgroups in Minitab

In Java, we can use the CountDownLatch class to achieve similar functionality to Go’s WaitGroups. This allows us to wait for multiple threads to finish their execution.

import java.util.concurrent.CountDownLatch;
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.
            TimeUnit.SECONDS.sleep(1);
            
            System.out.printf("Worker %d done%n", id);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            // Signal that this worker is done.
            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);

        // Launch several threads and decrement the CountDownLatch
        // counter for each.
        for (int i = 1; i <= 5; i++) {
            final int workerId = i;
            new Thread(() -> worker(workerId, latch)).start();
        }

        // Block until the CountDownLatch counter goes back to 0;
        // all the workers notified they're done.
        latch.await();

        // Note that this approach has no straightforward way
        // to propagate exceptions from workers. For more
        // advanced use cases, consider using the
        // ExecutorService and Future interfaces.
    }
}

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:

  1. We use CountDownLatch instead of WaitGroup. The CountDownLatch is initialized with the number of workers we expect.

  2. Each worker thread calls latch.countDown() when it’s done, which is equivalent to wg.Done() in the Go version.

  3. The main thread waits for all workers to finish by calling latch.await(), which is similar to wg.Wait() in Go.

  4. We use Java’s built-in Thread class to create and start new threads, which is analogous to using goroutines in Go.

  5. The TimeUnit.SECONDS.sleep(1) call is used to simulate an expensive task, similar to time.Sleep(time.Second) in the Go version.

This approach demonstrates how to coordinate multiple threads in Java, waiting for all of them to complete before proceeding. However, for more complex scenarios, you might want to consider using higher-level concurrency utilities provided by Java’s java.util.concurrent package, such as ExecutorService and Future.