CompletableFuture异常优雅处理方式

参考:

CompletableFuture异常优雅处理方式_completablefuture异常处理_wenqizai的博客-CSDN博客

package com.corpgovernment.InitInterface;

import jodd.util.concurrent.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class T_001 {
    private static final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("my-pool-%d").get();
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 10,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    // private static final List<Integer> resultList = new ArrayList<>();
    private static final List<Integer> resultList = Collections.synchronizedList(new ArrayList<>());
    private static final List<CompletableFuture<Integer>> futureList = new ArrayList<>();


    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        try {
            doSomething(executor, resultList, futureList);
        } catch (Exception e) {
            System.out.println("main 处理了异常 -> " + e.getMessage());
        }
        System.out.println("方法执行时间: " + (System.currentTimeMillis() - start));
        System.out.println("main 执行完了...");
        executor.shutdown();
    }


    public static void doSomething(ThreadPoolExecutor executor, List<Integer> resultList,
                                   List<CompletableFuture<Integer>> futureList) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
                try {
                    Thread.sleep(finalI * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (finalI == 4) {
                    System.out.println("业务异常... -> " + finalI);
                    throw new RuntimeException("业务异常... -> " + finalI);
                }
                return finalI;
            }, executor).handle((result, e) -> {
                if (e != null) {
                    sb.append("CompletableFuture处理异常 -> " + e.getCause().getMessage());
                    throw new RuntimeException("CompletableFuture处理异常 -> " + e.getMessage());
                }
                resultList.add(result);
                return result;
            });
            futureList.add(future);
        }

        CompletableFuture<Void> completableFuture = CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0]));
        if (completableFuture.isCompletedExceptionally()) {
            throw new RuntimeException(sb.toString());
        } else {
            resultList.addAll(futureList.stream().map(CompletableFuture::join).collect(Collectors.toList()));
        }
        System.out.println(resultList);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值