LatchUtils: Simplify Java Async Task Synchronization with One Utility Class
This article introduces LatchUtils, a lightweight Java utility that streamlines waiting for multiple asynchronous tasks by registering tasks first and then blocking once, comparing it against manual CountDownLatch and CompletableFuture approaches with code examples and a detailed feature comparison.
Introduction
In Java application development, improving performance and responsiveness often requires executing time-consuming operations — such as external API calls, database queries, or complex calculations — asynchronously in parallel. When the main flow must wait for all parallel tasks to finish, developers typically use ExecutorService and CountDownLatch. However, direct use of these low-level tools leads to repetitive boilerplate code that obscures business logic.
To address this, the author encapsulates a lightweight utility class named LatchUtils that organizes and manages such asynchronous tasks with minimal ceremony.
Detailed Code
The complete implementation of LatchUtils:
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
public class LatchUtils {
private static final ThreadLocal<List<TaskInfo>> THREADLOCAL = ThreadLocal.withInitial(LinkedList::new);
public static void submitTask(Executor executor, Runnable runnable) {
THREADLOCAL.get().add(new TaskInfo(executor, runnable));
}
private static List<TaskInfo> popTask() {
List<TaskInfo> taskInfos = THREADLOCAL.get();
THREADLOCAL.remove();
return taskInfos;
}
public static boolean waitFor(long timeout, TimeUnit timeUnit) {
List<TaskInfo> taskInfos = popTask();
if (taskInfos.isEmpty()) {
return true;
}
CountDownLatch latch = new CountDownLatch(taskInfos.size());
for (TaskInfo taskInfo : taskInfos) {
Executor executor = taskInfo.executor;
Runnable runnable = taskInfo.runnable;
executor.execute(() -> {
try {
runnable.run();
} finally {
latch.countDown();
}
});
}
boolean await = false;
try {
await = latch.await(timeout, timeUnit);
} catch (Exception ignored) {
}
return await;
}
private static final class TaskInfo {
private final Executor executor;
private final Runnable runnable;
public TaskInfo(Executor executor, Runnable runnable) {
this.executor = executor;
this.runnable = runnable;
}
}
}Core Idea
The design philosophy of LatchUtils is: submit multiple times, wait once .
Task Registration: In the main flow, call LatchUtils.submitTask(executor, runnable) to register each asynchronous task along with the Executor that will run it.
Execute and Wait: After all tasks are submitted, call LatchUtils.waitFor(timeout, timeUnit) once. This method immediately triggers execution of all registered tasks and blocks until all complete or the timeout expires.
API Overview
The utility exposes only two core static methods:
submitTask(Executor executor, Runnable runnable)
Submits an asynchronous task. executor ( java.util.concurrent.Executor) — the thread pool to execute this task. runnable ( java.lang.Runnable) — the business logic to run asynchronously.
waitFor(long timeout, TimeUnit timeUnit)
Triggers execution of all submitted tasks and waits synchronously for completion. timeout ( long) — maximum time to wait. timeUnit ( java.util.concurrent.TimeUnit) — unit of the timeout.
Returns true if all tasks finish within the timeout; false on timeout.
After execution, the method automatically clears the current thread's task list, allowing reuse.
Practical Example
A typical scenario: an aggregation service calls User, Order, and Product services in parallel, then proceeds when all results are ready.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
// 1. Prepare a thread pool
ExecutorService executorService = Executors.newFixedThreadPool(3);
System.out.println("主流程开始,准备分发异步任务...");
// 2. Submit multiple async tasks
// Task 1: fetch user info
LatchUtils.submitTask(executorService, () -> {
try {
System.out.println("开始获取用户信息...");
Thread.sleep(1000); // simulate latency
System.out.println("获取用户信息成功!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// Task 2: fetch order info
LatchUtils.submitTask(executorService, () -> {
try {
System.out.println("开始获取订单信息...");
Thread.sleep(1500);
System.out.println("获取订单信息成功!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// Task 3: fetch product info
LatchUtils.submitTask(executorService, () -> {
try {
System.out.println("开始获取商品信息...");
Thread.sleep(500);
System.out.println("获取商品信息成功!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
System.out.println("所有异步任务已提交,主线程开始等待...");
// 3. Wait for all tasks, max 5 seconds
boolean allTasksCompleted = LatchUtils.waitFor(5, TimeUnit.SECONDS);
// 4. Continue main flow based on result
if (allTasksCompleted) {
System.out.println("所有异步任务执行成功,主流程继续...");
} else {
System.err.println("有任务执行超时,主流程中断!");
}
// 5. Shutdown thread pool
executorService.shutdown();
}
}Output:
主流程开始,准备分发异步任务...
所有异步任务已提交,主线程开始等待...
开始获取商品信息...
开始获取用户信息...
开始获取订单信息...
获取商品信息成功!
获取用户信息成功!
获取订单信息成功!
所有异步任务执行成功,主流程继续...The business code stays clean — developers only focus on "submit task" and "wait for results", without managing CountDownLatch initialization, countDown() calls, or exception handling details.
Comparison: Without LatchUtils
To illustrate the value, the article shows two traditional implementations for the same scenario.
Approach 1: Manual CountDownLatch
Developers must manually manage the CountDownLatch lifecycle:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ManualCountDownLatchExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
// Manually initialize CountDownLatch with task count
CountDownLatch latch = new CountDownLatch(3);
System.out.println("主流程开始,准备分发异步任务...");
// Submit tasks, each calling latch.countDown() in finally
executorService.execute(() -> {
try {
System.out.println("开始获取用户信息...");
Thread.sleep(1000);
System.out.println("获取用户信息成功!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
latch.countDown(); // manual decrement
}
});
// ... similar for order and product tasks ...
System.out.println("所有异步任务已提交,主线程开始等待...");
// Manual await with exception handling
boolean allTasksCompleted = false;
try {
allTasksCompleted = latch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("主线程在等待时被中断!");
}
if (allTasksCompleted) {
System.out.println("所有异步任务执行成功,主流程继续...");
} else {
System.err.println("有任务执行超时,主流程中断!");
}
executorService.shutdown();
}
}Approach 2: CompletableFuture.allOf
Using CompletableFuture:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CompletableFutureExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
System.out.println("主流程开始,准备分发异步任务...");
// Create CompletableFuture tasks
CompletableFuture<Void> userFuture = CompletableFuture.runAsync(() -> {
try {
System.out.println("开始获取用户信息...");
Thread.sleep(1000);
System.out.println("获取用户信息成功!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, executorService);
CompletableFuture<Void> orderFuture = CompletableFuture.runAsync(() -> {
try {
System.out.println("开始获取订单信息...");
Thread.sleep(1500);
System.out.println("获取订单信息成功!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, executorService);
CompletableFuture<Void> productFuture = CompletableFuture.runAsync(() -> {
try {
System.out.println("开始获取商品信息...");
Thread.sleep(500);
System.out.println("获取商品信息成功!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, executorService);
System.out.println("所有异步任务已提交,主线程开始等待...");
// Combine all futures
CompletableFuture<Void> allFutures = CompletableFuture.allOf(userFuture, orderFuture, productFuture);
// Wait for combined future
try {
allFutures.get(5, TimeUnit.SECONDS);
System.out.println("所有异步任务执行成功,主流程继续...");
} catch (Exception e) {
System.err.println("任务执行超时或出错,主流程中断! " + e.getMessage());
}
executorService.shutdown();
}
}Comparative Analysis
The article provides a feature-by-feature comparison:
Code Conciseness: LatchUtils — Very High (business logic separated from concurrency control); Manual CountDownLatch — Medium (countDown() scattered in tasks); CompletableFuture — High (fluent API but requires multiple Future objects).
State Management: LatchUtils — Automatic (internal CountDownLatch); Manual — Manual (create, maintain, pass latch); CompletableFuture — Automatic (framework-managed).
Error Handling: LatchUtils — Simplified (waitFor swallows InterruptedException, returns boolean); Manual — Complex (finally countDown() + explicit await() exception handling); CompletableFuture — Complex (get() throws multiple checked exceptions).
Separation of Concerns: LatchUtils — Excellent (only "submit" and "wait"); Manual — Fair (concurrency logic invades business Runnable); CompletableFuture — Good (task definition separate from composition, but still handle combined Future).
Ease of Use: LatchUtils — Very Simple (almost zero learning curve); Manual — Requires CountDownLatch knowledge (easy to forget countDown() or mishandle exceptions); CompletableFuture — Requires CompletableFuture knowledge (richer API, steeper learning curve).
Conclusion
For the common pattern of "dispatch a group of parallel tasks and wait for all to complete", LatchUtils provides a focused abstraction that hides concurrency complexity, letting business code express its intent directly. This improves readability and maintainability without sacrificing control.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
