Question
How can I implement functionality in Java that is similar to Golang's WaitGroup?
// Golang WaitGroup example
var wg sync.WaitGroup
for _, task := range tasks {
wg.Add(1)
go func(t Task) {
defer wg.Done()
// process t
}(task)
}
wg.Wait()
Answer
In Golang, the `WaitGroup` is a concurrency primitive used to wait for a collection of goroutines to finish executing. The equivalent functionality in Java can be achieved using the `CountDownLatch` or `ExecutorService` classes from the `java.util.concurrent` package. These classes help manage concurrent tasks and ensure that your main execution thread waits for all tasks to complete before proceeding.
import java.util.concurrent.CountDownLatch;
public class WaitGroupExample {
public static void main(String[] args) throws InterruptedException {
int numberOfTasks = 5;
CountDownLatch latch = new CountDownLatch(numberOfTasks);
for (int i = 0; i < numberOfTasks; i++) {
new Thread(() -> {
try {
// Simulating work
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
latch.countDown(); // Decrement the count
}
}).start();
}
latch.await(); // Wait for all tasks to complete
System.out.println("All tasks completed!");
}
}
Causes
- Golang's WaitGroup is designed for synchronizing multiple concurrent operations in a processing pipeline.
- Java lacks a direct equivalent of WaitGroup but provides tools like CountDownLatch and ExecutorService for similar functionality.
Solutions
- Use `CountDownLatch` to wait for a specific number of operations to complete before proceeding.
- Utilize `ExecutorService` to manage a pool of threads and invoke `awaitTermination` to wait for all tasks.
Common Mistakes
Mistake: Forgetting to call `countDown()` in the worker threads, leading to indefinite waiting.
Solution: Ensure that `countDown()` is called in a `finally` block to guarantee execution.
Mistake: Using an incorrect count in `CountDownLatch`, which leads to premature completion.
Solution: Always set the latch count to the exact number of tasks you're waiting for.
Helpers
- Golang WaitGroup
- Java CountDownLatch
- Java ExecutorService
- Concurrency in Java
- Java thread synchronization