zoukankan      html  css  js  c++  java
  • CompletableFuture.allOf方法,future的handler有没有执行问题

    文章目录

    场景

    在分片上传的时候,有返回对应的etag,所以,我需要在分片上传完成之后,对返回的数据进行封装,封装完成后调最后的完成接口.
    出现问题,总是缺少部分分片,偶尔会报错…

    模拟

    for循环创建CompletableFuture,然后执行allOf方法看看
    代码:

     @Test
      public void allOfTest2() throws Exception {
        List<CompletableFuture> comlist = new ArrayList<>();
        int size = 3;
        CountDownLatch countDownLatch = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
          final int res = i;
          CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> {
            try {
              TimeUnit.SECONDS.sleep(3);
              System.out.println(System.currentTimeMillis() + ":" + res + "执行完成");
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            return res + "";
          });
          f1.whenCompleteAsync((x, y) -> {
            try {
              TimeUnit.SECONDS.sleep(1);
              System.out.println(System.currentTimeMillis() + ":" + x + "回调执行完成");
              countDownLatch.countDown();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          });
          comlist.add(f1);
        }
    
        CompletableFuture<Void> all = CompletableFuture.allOf(comlist.toArray(new CompletableFuture[size]));
        //阻塞,直到所有任务结束。任务complete就会执行,handler里面不一定会执行..
        System.out.println(System.currentTimeMillis() + ":阻塞");
        all.join();
        System.out.println(System.currentTimeMillis() + ":阻塞结束");
        countDownLatch.await();
        System.out.println("回调都结束...");
      }
    

    执行结果:

    在这里插入图片描述

    结论

    发现当执行完成之后,allof返回的就会结束,并不会等待回调方法也执行完成…
    所以,一般使用allof方法的时候,都是消费Action,一般不会对结果进行处理,如果对结果进行处理,那肯定会发生错误…

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    Codeforces 631A Interview【模拟水题】
    Codeforces 651E Table Compression【并查集】
    Codeforces 651D Image Preview【二分+枚举】
    Codeforces 651C Watchmen【模拟】
    Codeforces 651B Beautiful Paintings【贪心】
    18.06.26 16年期末10:游览规划
    18.06.25 POJ4129 16年期末09:变换的迷宫
    18.06.25 POJ4150 16年期末07:上机
    18.06.25 16年期末06 42点
    18.06.25 16年期末01-05集合
  • 原文地址:https://www.cnblogs.com/javayida/p/13346756.html
Copyright © 2011-2022 走看看