• CompletableFuture CompletableFuture.supplyAsync 异常处理


    CompletableFuture 异常处理completeExceptionally可以把异常抛到主线程
    /**
     * User: laizhenwei
     * Date: 2018-01-30 Time: 22:26
     * Description:
     */
    @RunWith(SpringRunner.class)
    //@SpringBootTest
    public class CompletableFutureTests {
    
        @Test
        public void testMethod() {
    
            String[] orders = {"1", "2", "3", "4", "5", "6"};
    
            List<CompletableFuture<Boolean>> futures = new ArrayList<>();
    
            Arrays.stream(orders).forEach(id -> {
                try{
                    futures.add(submitAsync(id));
                }catch (Exception ex){
                    System.out.println(ex);
                }
            });
    
            futures.stream().forEach(f-> {
                try {
                    System.out.println(f.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    
        private static Boolean submit(String order) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            throw new RuntimeException("抛一个异常" + order);
        }
    
        private static CompletableFuture<Boolean> submitAsync(String order) {
            CompletableFuture<Boolean> future = new CompletableFuture<>();
            new Thread(() -> {
                try {
                    Boolean result = submit(order);
                    future.complete(result);
                } catch (Exception ex) {
                    future.completeExceptionally(ex);
                }
            }).start();
            return future;
        }
    
    }

     

    使用 CompletableFuture.supplyAsync  简化代码 加入线程池,exceptionally处理异常

    /**
     * User: laizhenwei
     * Date: 2018-01-30 Time: 22:26
     * Description:
     */
    @RunWith(SpringRunner.class)
    //@SpringBootTest
    public class CompletableFutureTests {
    
        ExecutorService executor = Executors.newFixedThreadPool(3);
    
        @Test
        public void testMethod() {
            String[] orders = {"1", "2", "3", "4", "5", "6"};
            Arrays.stream(orders).forEach(id -> CompletableFuture.supplyAsync(() -> submit(id), executor).exceptionally(e -> {
                System.out.println(e);
                return false;
            }));
    
            executor.shutdown();
            while (!executor.isTerminated()) {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private static Boolean submit(String order) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            throw new RuntimeException("抛一个异常" + order);
        }
    
    }

  • 相关阅读:
    数据库三大范式另一角度的理解
    Log4j和Slf4j的联系和区别
    cglib和Jdk的对比
    Git- 忽略文件 ignore 无效
    GIT报错:git did not exit cleanly (exit code 1)
    Nginx和Zuul配合使用后,Cookie写入问题
    RabbitMQ报错:undefined: There is no template at js/tmpl/login.ejs
    Feign报错:The bean 'xxxxx.FeignClientSpecification' could not be registered.
    ES报错:NoNodeAvailableException[None of the configured nodes are available
    SpringBoot报错:
  • 原文地址:https://www.cnblogs.com/sweetchildomine/p/8387724.html
Copyright © 2020-2023  润新知