CompletableFuture的使用
CompletableFuture实现了Future和CompletionStage接口,提供了丰富的异步编程能力:
- 支持任务链式调用
- 提供多任务组合操作
- 内置异常处理机制
- 可以指定执行线程池
实际应用示例
public class AsyncService {
private final ThreadPoolExecutor executor;
public AsyncService() {
// 创建IO密集型任务的线程池
int processors = Runtime.getRuntime().availableProcessors();
executor = new ThreadPoolExecutor(
processors * 2,
processors * 4,
60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1000),
new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("async-service-" + counter.getAndIncrement());
thread.setDaemon(true);
return thread;
}
},
new ThreadPoolExecutor.CallerRunsPolicy()
);
}
public CompletableFuture<User> getUserAsync(Long userId) {
return CompletableFuture.supplyAsync(() -> {
// 模拟数据库查询
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new User(userId, "用户" + userId);
}, executor);
}
public CompletableFuture<Order> getOrderAsync(Long orderId) {
return CompletableFuture.supplyAsync(() -> {
// 模拟数据库查询
try {
Thread.sleep(150);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new Order(orderId, "订单" + orderId);
}, executor);
}
// 并行查询用户和订单信息
public CompletableFuture<UserOrderDetail> getUserOrderDetail(Long userId, Long orderId) {
CompletableFuture<User> userFuture = getUserAsync(userId);
CompletableFuture<Order> orderFuture = getOrderAsync(orderId);
return userFuture.thenCombineAsync(orderFuture,
(user, order) -> new UserOrderDetail(user, order), executor);
}
// 记得在应用关闭时关闭线程池
public void shutdown() {
executor.shutdown();
}
}

浙公网安备 33010602011771号