多个任务同同时异步处理+等待处理完毕
1.多个任务同时异步处理
// 设计线程池最大5个并发,其他进来排队
private ExecutorService executorPool = ThreadUtils.newDaemonFixedThreadPool(5,"APP-SCAN-THREAD");
private void commitAsyncScanRequests(List<CompletableFuture<List<AppHealthScanResult>>> futures, List<AppHealthRequest> requests) {
for (AppHealthRequest request : requests) {
CompletableFuture<List<AppHealthScanResult>> future = CompletableFuture.supplyAsync(
() -> getAppHealthScanResult(request), executorPool);
futures.add(future);
}
}
2.等待结果处理完毕
private void waitScanRequestComplete(List<CompletableFuture<List<AppHealthScanResult>>> futures) {
log.info("应用健康度扫描等待所有扫描结果{}完成", futures.size());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
}
3.获取多个任务的处理结果
private void writeScanResults(List<AppHealthScanResult> scanResults, List<CompletableFuture<List<AppHealthScanResult>>> futures) throws InterruptedException, ExecutionException {
for (CompletableFuture<List<AppHealthScanResult>> future : futures) {
scanResults.addAll(future.get());
}
}
4.所有逻辑组装起来
private BiConsumer<List<AppHealthRequest>,List<AppHealthScanResult>> appHealthCheckConsumer = new BiConsumer<List<AppHealthRequest>, List<AppHealthScanResult>>() {
@SneakyThrows
@Override
public void accept(List<AppHealthRequest> requests, List<AppHealthScanResult> scanResults) {
List<CompletableFuture<List<AppHealthScanResult>>> futures = Lists.newCopyOnWriteArrayList();
// 提交异步扫描请求
commitAsyncScanRequests(futures,requests);
// 等待扫描完成
waitScanRequestComplete(futures);
// 获取扫描结果
writeScanResults(scanResults,futures);
log.info("应用健康度扫描所有扫描结果完成");
}
};
原创:做时间的朋友