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 resultList = new ArrayList<>();
    private static final List resultList = Collections.synchronizedList(new ArrayList<>());
    private static final List> 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 resultList,
                                   List> futureList) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            CompletableFuture 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 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);
    }

}

你可能感兴趣的:(java)