在java应用开发中,为了提升系统性能和响应速度,我们经常需要将一些耗时操作(如调用外部api、查询数据库、复杂计算等)进行异步并行处理。当主流程需要等待所有这些并行任务执行完毕后再继续时,我们通常会用到 executorservice、 countdownlatch 等并发工具。
然而,直接使用这些原生工具,往往意味着需要编写一些重复的、模式化的“胶水代码”,这不仅增加了代码量,也让核心业务逻辑显得不够清晰。
为了解决这个问题,我封装了一个名为 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;
}
}
}核心思想
latchutils 的设计哲学是:多次提交,一次等待。
- 任务注册: 在主流程代码中,可以先通过 latchutils.submittask() 提交runnable任务和其对应的executor(该线程池用来执行这个runnable)。
- 执行并等待: 当并行任务都提交完毕后,你只需调用一次 latchutils.waitfor()。关注工众号:码猿技术专栏,回复关键词:1111 获取阿里内部java性能调优手册!该方法会立即触发所有已注册任务的执行,并阻塞等待所有任务执行完成或超时。
api 概览
这个工具类对外暴露的接口极其简单,只有两个核心静态方法:
submittask()
public static void submittask(executor executor, runnable runnable)
功能: 提交一个异步任务。
参数:
- executor:java.util.concurrent.executor - 指定执行此任务的线程池。
- runnable:java.lang.runnable - 需要异步执行的具体业务逻辑。
waitfor()
public static boolean waitfor(long timeout, timeunit timeunit)
功能: 触发所有已提交任务的执行,并同步等待它们全部完成。
参数:
- timeout:
long- 最长等待时间。 - timeunit:
java.util.concurrent.timeunit- 等待时间单位。
返回值:
- true: 如果所有任务在指定时间内成功完成。
- false: 如果等待超时。
注意: 该方法在执行后会自动清理当前线程提交的任务列表,因此可以重复使用。
实战示例
让我们来看一个典型的应用场景:一个聚合服务需要同时调用用户服务、订单服务和商品服务,拿到所有结果后再进行下一步处理。
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. 准备一个线程池
executorservice executorservice = executors.newfixedthreadpool(3);
system.out.println("主流程开始,准备分发异步任务...");
// 2. 提交多个异步任务
// 任务一:获取用户信息
latchutils.submittask(executorservice, () -> {
try {
system.out.println("开始获取用户信息...");
thread.sleep(1000); // 模拟耗时
system.out.println("获取用户信息成功!");
} catch (interruptedexception e) {
thread.currentthread().interrupt();
}
});
// 任务二:获取订单信息
latchutils.submittask(executorservice, () -> {
try {
system.out.println("开始获取订单信息...");
thread.sleep(1500); // 模拟耗时
system.out.println("获取订单信息成功!");
} catch (interruptedexception e) {
thread.currentthread().interrupt();
}
});
// 任务三:获取商品信息
latchutils.submittask(executorservice, () -> {
try {
system.out.println("开始获取商品信息...");
thread.sleep(500); // 模拟耗时
system.out.println("获取商品信息成功!");
} catch (interruptedexception e) {
thread.currentthread().interrupt();
}
});
system.out.println("所有异步任务已提交,主线程开始等待...");
// 3. 等待所有任务完成,最长等待5秒
boolean alltaskscompleted = latchutils.waitfor(5, timeunit.seconds);
// 4. 根据等待结果继续主流程
if (alltaskscompleted) {
system.out.println("所有异步任务执行成功,主流程继续...");
} else {
system.err.println("有任务执行超时,主流程中断!");
}
// 5. 关闭线程池
executorservice.shutdown();
}
}输出结果:
主流程开始,准备分发异步任务...
所有异步任务已提交,主线程开始等待...
开始获取商品信息...
开始获取用户信息...
开始获取订单信息...
获取商品信息成功!
获取用户信息成功!
获取订单信息成功!
所有异步任务执行成功,主流程继续...
从这个例子中可以看到,业务代码变得非常清晰。我们只需要关注“提交任务”和“等待结果”这两个动作,而无需关心 countdownlatch 的初始化、countdown() 的调用以及异常处理等细节。
对比:如果不使用 latchutils
为了更好地理解 latchutils 带来的价值,让我们看看要实现与上面完全相同的功能,用传统的java并发api需要如何编写代码。
通常有两种主流方式:使用 countdownlatch 或使用 completablefuture。
方式一:直接使用 countdownlatch
这是最经典的方式,开发者需要手动管理 countdownlatch 的生命周期。
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) {
// 1. 准备一个线程池
executorservice executorservice = executors.newfixedthreadpool(3);
// 2. 手动初始化 countdownlatch,数量为任务数
countdownlatch latch = new countdownlatch(3);
system.out.println("主流程开始,准备分发异步任务...");
// 3. 提交任务,并在每个任务的 finally 块中手动调用 latch.countdown()
// 任务一:获取用户信息
executorservice.execute(() -> {
try {
system.out.println("开始获取用户信息...");
thread.sleep(1000);
system.out.println("获取用户信息成功!");
} catch (interruptedexception e) {
thread.currentthread().interrupt();
} finally {
latch.countdown(); // 手动减一
}
});
// 任务二:获取订单信息
executorservice.execute(() -> {
try {
system.out.println("开始获取订单信息...");
thread.sleep(1500);
system.out.println("获取订单信息成功!");
} catch (interruptedexception e) {
thread.currentthread().interrupt();
} finally {
latch.countdown(); // 手动减一
}
});
// 任务三:获取商品信息
executorservice.execute(() -> {
try {
system.out.println("开始获取商品信息...");
thread.sleep(500);
system.out.println("获取商品信息成功!");
} catch (interruptedexception e) {
thread.currentthread().interrupt();
} finally {
latch.countdown(); // 手动减一
}
});
system.out.println("所有异步任务已提交,主线程开始等待...");
// 4. 手动调用 latch.await() 进行等待
boolean alltaskscompleted = false;
try {
alltaskscompleted = latch.await(5, timeunit.seconds);
} catch (interruptedexception e) {
// 需要处理中断异常
thread.currentthread().interrupt();
system.err.println("主线程在等待时被中断!");
}
// 5. 根据等待结果继续主流程
if (alltaskscompleted) {
system.out.println("所有异步任务执行成功,主流程继续...");
} else {
system.err.println("有任务执行超时,主流程中断!");
}
// 6. 关闭线程池
executorservice.shutdown();
}
}方式二:使用 completablefuture
使用 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) {
// 1. 准备一个线程池
executorservice executorservice = executors.newfixedthreadpool(3);
system.out.println("主流程开始,准备分发异步任务...");
// 2. 创建 completablefuture 任务
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("所有异步任务已提交,主线程开始等待...");
// 3. 使用 completablefuture.allof 将所有任务组合起来
completablefuture<void> allfutures = completablefuture.allof(userfuture, orderfuture, productfuture);
// 4. 等待组合后的 future 完成
try {
allfutures.get(5, timeunit.seconds);
system.out.println("所有异步任务执行成功,主流程继续...");
} catch (exception e) {
// 需要处理多种异常,如 interruptedexception, executionexception, timeoutexception
system.err.println("任务执行超时或出错,主流程中断! " + e.getmessage());
}
// 5. 关闭线程池
executorservice.shutdown();
}
}对比分析
特性 | latchutils | 手动countdownlatch | completablefuture.allof |
|---|---|---|---|
| 代码简洁性 | 极高 。业务逻辑和并发控制分离,核心代码清晰。 | 中等 。需要在每个任务中嵌入latch.countdown(),分散了关注点。 | 较高 。链式调用风格,但需要创建多个future对象。 |
| 状态管理 | 自动 。工具类内部自动管理countdownlatch。 | 手动 。需要自己创建、维护和传递countdownlatch实例。 | 自动 。由completablefuture框架管理任务状态。 |
| 错误处理 | 简化 。waitfor内部处理interruptedexception,仅返回布尔值。 | 复杂 。需要显式地在finally中countdown(),并为主线程的await()处理interruptedexception。 | 复杂 。get()方法会抛出多种受检异常,需要统一处理。 |
| 关注点分离 | 优秀 。开发者只需关注“提交”和“等待”两个动作。 | 一般 。并发控制逻辑(countdown())侵入到了业务runnable中。 | 良好 。任务的定义和组合是分开的,但仍需处理组合后的future。 |
| 易用性 | 非常简单 。几乎没有学习成本。 | 需要理解countdownlatch 。容易忘记countdown()或错误处理。 | 需要理解completablefuture 。api较为丰富,有一定学习曲线。 |
结论很明显:
对于“分发一组并行任务,然后等待它们全部完成”这一特定但常见的模式,latchutils 通过适度的封装,极大地简化了开发者的工作。它隐藏了并发控制的复杂性,让业务代码回归其本质,从而提高了代码的可读性和可维护性。
到此这篇关于java并发神器latchutils搞定复杂异步同步的文章就介绍到这了,更多相关java latchutils并发内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论