范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文

代替Future的CompletableFuture让你的代码免受阻塞之苦

  通过阅读本篇文章你将了解到:  CompletableFuture的使用  CompletableFure异步和同步的性能测试  已经有了Future为什么仍需要在JDK1.8中引入CompletableFuture  CompletableFuture的应用场景  对CompletableFuture的使用优化  场景说明
  查询所有商店某个商品的价格并返回,并且查询商店某个商品的价格的API为同步 一个Shop类,提供一个名为getPrice的同步方法  店铺类:Shop.java  public class Shop {     private Random random = new Random();     /**      * 根据产品名查找价格      * */     public double getPrice(String product) {         return calculatePrice(product);     }      /**      * 计算价格      *      * @param product      * @return      * */     private double calculatePrice(String product) {         delay();         //random.nextDouble()随机返回折扣         return random.nextDouble() * product.charAt(0) + product.charAt(1);     }      /**      * 通过睡眠模拟其他耗时操作      * */     private void delay() {         try {             Thread.sleep(1000);         } catch (InterruptedException e) {             e.printStackTrace();         }     } }
  查询商品的价格为同步方法,并通过sleep方法模拟其他操作。这个场景模拟了当需要调用第三方API,但第三方提供的是同步API,在无法修改第三方API时如何设计代码调用提高应用的性能和吞吐量,这时候可以使用CompletableFuture类  CompletableFuture使用
  Completable是Future接口的实现类,在JDK1.8中引入  CompletableFuture的创建: 说明:  两个重载方法之间的区别 => 后者可以传入自定义Executor,前者是默认的,使用的ForkJoinPool  supplyAsync和runAsync方法之间的区别 => 前者有返回值,后者无返回值  Supplier是函数式接口,因此该方法需要传入该接口的实现类,追踪源码会发现在run方法中会调用该接口的方法。因此使用该方法创建CompletableFuture对象只需重写Supplier中的get方法,在get方法中定义任务即可。又因为函数式接口可以使用Lambda表达式,和new创建CompletableFuture对象相比代码会 简洁 不少 使用new方法      CompletableFuture futurePrice = new CompletableFuture<>(); 使用CompletableFuture#completedFuture静态方法创建      public static  CompletableFuture completedFuture(U value) {         return new CompletableFuture((value == null) ? NIL : value);     } 参数的值为任务执行完的结果,一般该方法在实际应用中较少应用 使用 CompletableFuture#supplyAsync静态方法创建 supplyAsync有两个重载方法:      //方法一     public static  CompletableFuture supplyAsync(Supplier supplier) {         return asyncSupplyStage(asyncPool, supplier);     }     //方法二     public static  CompletableFuture supplyAsync(Supplier supplier,                                                        Executor executor) {         return asyncSupplyStage(screenExecutor(executor), supplier);     } 使用CompletableFuture#runAsync静态方法创建 runAsync有两个重载方法      //方法一     public static CompletableFuture runAsync(Runnable runnable) {         return asyncRunStage(asyncPool, runnable);     }     //方法二     public static CompletableFuture runAsync(Runnable runnable, Executor executor) {         return asyncRunStage(screenExecutor(executor), runnable);     } 结果的获取:  对于结果的获取CompltableFuture类提供了四种方式   //方式一   public T get()   //方式二   public T get(long timeout, TimeUnit unit)   //方式三   public T getNow(T valueIfAbsent)   //方式四   public T join()
  说明:
  示例:  get()和get(long timeout, TimeUnit unit) => 在Future中就已经提供了,后者提供超时处理,如果在指定时间内未获取结果将抛出超时异常  getNow => 立即获取结果不阻塞,结果计算已完成将返回结果或计算过程中的异常,如果未计算完成将返回设定的valueIfAbsent值  join => 方法里不会抛出异常  public class AcquireResultTest {   public static void main(String[] args) throws ExecutionException, InterruptedException {       //getNow方法测试       CompletableFuture cp1 = CompletableFuture.supplyAsync(() -> {           try {               Thread.sleep(60 * 1000 * 60 );           } catch (InterruptedException e) {               e.printStackTrace();           }              return "hello world";       });          System.out.println(cp1.getNow("hello h2t"));          //join方法测试       CompletableFuture cp2 = CompletableFuture.supplyAsync((()-> 1 / 0));       System.out.println(cp2.join());          //get方法测试       CompletableFuture cp3 = CompletableFuture.supplyAsync((()-> 1 / 0));       System.out.println(cp3.get());   } }
  说明:  第一个执行结果为hello h2t,因为要先睡上1分钟结果不能立即获取  join方法获取结果方法里不会抛异常,但是执行结果会抛异常,抛出的异常为CompletionException  get方法获取结果方法里将抛出异常,执行结果抛出的异常为ExecutionException  异常处理:  使用静态方法创建的CompletableFuture对象无需显示处理异常,使用new创建的对象需要调用completeExceptionally方法设置捕获到的异常,举例说明: CompletableFuture completableFuture = new CompletableFuture(); new Thread(() -> {    try {        //doSomething,调用complete方法将其他方法的执行结果记录在completableFuture对象中        completableFuture.complete(null);    } catch (Exception e) {        //异常处理        completableFuture.completeExceptionally(e);     } }).start(); 同步方法Pick异步方法查询所有店铺某个商品价格
  店铺为一个列表:  private static List shopList = Arrays.asList(         new Shop("BestPrice"),         new Shop("LetsSaveBig"),         new Shop("MyFavoriteShop"),         new Shop("BuyItAll") );
  同步方法:  private static List findPriceSync(String product) {     return shopList.stream()             .map(shop -> String.format("%s price is %.2f",                     shop.getName(), shop.getPrice(product)))  //格式转换             .collect(Collectors.toList()); }
  异步方法:  private static List findPriceAsync(String product) {     List> completableFutureList = shopList.stream()             //转异步执行             .map(shop -> CompletableFuture.supplyAsync(                     () -> String.format("%s price is %.2f",                             shop.getName(), shop.getPrice(product))))  //格式转换             .collect(Collectors.toList());      return completableFutureList.stream()             .map(CompletableFuture::join)  //获取结果不会抛出异常             .collect(Collectors.toList()); }
  性能测试结果:  Find Price Sync Done in 4141 Find Price Async Done in 1033
  异步 执行效率提高四倍  为什么仍需要CompletableFuture
  在JDK1.8以前,通过调用线程池的submit方法可以让任务以异步的方式运行,该方法会返回一个Future对象,通过调用get方法获取异步执行的结果:  private static List findPriceFutureAsync(String product) {     ExecutorService es = Executors.newCachedThreadPool();     List> futureList = shopList.stream().map(shop -> es.submit(() -> String.format("%s price is %.2f",             shop.getName(), shop.getPrice(product)))).collect(Collectors.toList());      return futureList.stream()             .map(f -> {                 String result = null;                 try {                     result = f.get();                 } catch (InterruptedException e) {                     e.printStackTrace();                 } catch (ExecutionException e) {                     e.printStackTrace();                 }                  return result;             }).collect(Collectors.toList()); }
  既生瑜何生亮,为什么仍需要引入CompletableFuture?对于简单的业务场景使用Future完全没有,但是想将多个异步任务的计算结果组合起来,后一个异步任务的计算结果需要前一个异步任务的值等等,使用Future提供的那点API就囊中羞涩,处理起来不够优雅,这时候还是让CompletableFuture以 声明式 的方式优雅的处理这些需求。而且在Future编程中想要拿到Future的值然后拿这个值去做后续的计算任务,只能通过轮询的方式去判断任务是否完成这样非常占CPU并且代码也不优雅,用伪代码表示如下: while(future.isDone()) {     result = future.get();     doSomrthingWithResult(result); }
  但CompletableFuture提供了API帮助我们实现这样的需求  其他API介绍whenComplete计算结果的处理:
  对前面计算结果进行处理,无法返回新值 提供了三个方法:  //方法一 public CompletableFuture whenComplete(BiConsumer<? super T,? super Throwable> action) //方法二 public CompletableFuture whenCompleteAsync(BiConsumer<? super T,? super Throwable> action) //方法三 public CompletableFuture whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
  说明:  BiFunction<? super T,? super U,? extends V> fn参数 => 定义对结果的处理  Executor executor参数 => 自定义线程池  以async结尾的方法将会在一个新的线程中执行组合操作
  示例:  public class WhenCompleteTest {     public static void main(String[] args) {         CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> "hello");         CompletableFuture cf2 = cf1.whenComplete((v, e) ->                 System.out.println(String.format("value:%s, exception:%s", v, e)));         System.out.println(cf2.join());     } }thenApply转换:
  将前面计算结果的的CompletableFuture传递给thenApply,返回thenApply处理后的结果。可以认为通过thenApply方法实现 CompletableFuture 至CompletableFuture 的转换。白话一点就是将CompletableFuture的计算结果作为thenApply方法的参数,返回thenApply方法处理后的结果 提供了三个方法: //方法一 public  CompletableFuture thenApply(     Function<? super T,? extends U> fn) {     return uniApplyStage(null, fn); }  //方法二 public  CompletableFuture thenApplyAsync(     Function<? super T,? extends U> fn) {     return uniApplyStage(asyncPool, fn); }  //方法三 public  CompletableFuture thenApplyAsync(     Function<? super T,? extends U> fn, Executor executor) {     return uniApplyStage(screenExecutor(executor), fn); }
  说明:  Function<? super T,? extends U> fn参数 => 对前一个CompletableFuture 计算结果的转化操作  Executor executor参数 => 自定义线程池  以async结尾的方法将会在一个新的线程中执行组合操作 示例:  public class ThenApplyTest {     public static void main(String[] args) throws ExecutionException, InterruptedException {         CompletableFuture result = CompletableFuture.supplyAsync(ThenApplyTest::randomInteger).thenApply((i) -> i * 8);         System.out.println(result.get());     }      public static Integer randomInteger() {         return 10;     } }
  这里将前一个CompletableFuture计算出来的结果扩大八倍  thenAccept结果处理:
  thenApply也可以归类为对结果的处理,thenAccept和thenApply的区别就是没有返回值 提供了三个方法:  //方法一 public CompletableFuture thenAccept(Consumer<? super T> action) {     return uniAcceptStage(null, action); }  //方法二 public CompletableFuture thenAcceptAsync(Consumer<? super T> action) {     return uniAcceptStage(asyncPool, action); }  //方法三 public CompletableFuture thenAcceptAsync(Consumer<? super T> action,                                                Executor executor) {     return uniAcceptStage(screenExecutor(executor), action); }
  说明:  Consumer<? super T> action参数 => 对前一个CompletableFuture计算结果的操作  Executor executor参数 => 自定义线程池  同理以async结尾的方法将会在一个新的线程中执行组合操作 示例:  public class ThenAcceptTest {     public static void main(String[] args) {         CompletableFuture.supplyAsync(ThenAcceptTest::getList).thenAccept(strList -> strList.stream()                 .forEach(m -> System.out.println(m)));     }      public static List getList() {         return Arrays.asList("a", "b", "c");     } }
  将前一个CompletableFuture计算出来的结果打印出来  thenCompose异步结果流水化:
  thenCompose方法可以将两个异步操作进行流水操作 提供了三个方法:  //方法一 public  CompletableFuture thenCompose(     Function<? super T, ? extends CompletionStage> fn) {     return uniComposeStage(null, fn); }  //方法二 public  CompletableFuture thenComposeAsync(     Function<? super T, ? extends CompletionStage> fn) {     return uniComposeStage(asyncPool, fn); }  //方法三 public  CompletableFuture thenComposeAsync(     Function<? super T, ? extends CompletionStage> fn,     Executor executor) {     return uniComposeStage(screenExecutor(executor), fn); }
  说明:  Function<? super T, ? extends CompletionStage> fn 参数 => 当前CompletableFuture计算结果的执行 Executor executor参数 => 自定义线程池  同理以async结尾的方法将会在一个新的线程中执行组合操作 示例:  public class ThenComposeTest {     public static void main(String[] args) throws ExecutionException, InterruptedException {         CompletableFuture result = CompletableFuture.supplyAsync(ThenComposeTest::getInteger)                 .thenCompose(i -> CompletableFuture.supplyAsync(() -> i * 10));         System.out.println(result.get());     }      private static int getInteger() {         return 666;     }      private static int expandValue(int num) {         return num * 10;     } }
  执行流程图:
  thenCombine组合结果:
  thenCombine方法将两个无关的CompletableFuture组合起来,第二个Completable并不依赖第一个Completable的结果 提供了三个方法:  //方法一 public  CompletableFuture thenCombine(      CompletionStage<? extends U> other,     BiFunction<? super T,? super U,? extends V> fn) {     return biApplyStage(null, other, fn); }   //方法二   public  CompletableFuture thenCombineAsync(       CompletionStage<? extends U> other,       BiFunction<? super T,? super U,? extends V> fn) {       return biApplyStage(asyncPool, other, fn);   }    //方法三   public  CompletableFuture thenCombineAsync(       CompletionStage<? extends U> other,       BiFunction<? super T,? super U,? extends V> fn, Executor executor) {       return biApplyStage(screenExecutor(executor), other, fn);   }
  说明:  CompletionStage<? extends U> other参数 => 新的CompletableFuture的计算结果  BiFunction<? super T,? super U,? extends V> fn参数 => 定义了两个CompletableFuture对象 完成计算后 如何合并结果,该参数是一个函数式接口,因此可以使用Lambda表达式 Executor executor参数 => 自定义线程池  同理以async结尾的方法将会在一个新的线程中执行组合操作
  示例:  public class ThenCombineTest {     private static Random random = new Random();     public static void main(String[] args) throws ExecutionException, InterruptedException {         CompletableFuture result = CompletableFuture.supplyAsync(ThenCombineTest::randomInteger).thenCombine(                 CompletableFuture.supplyAsync(ThenCombineTest::randomInteger), (i, j) -> i * j         );          System.out.println(result.get());     }      public static Integer randomInteger() {         return random.nextInt(100);     } }
  将两个线程计算出来的值做一个乘法在返回 执行流程图:
  allOf&anyOf组合多个CompletableFuture:
  方法介绍:  //allOf public static CompletableFuture allOf(CompletableFuture<?>... cfs) {     return andTree(cfs, 0, cfs.length - 1); } //anyOf public static CompletableFuture anyOf(CompletableFuture<?>... cfs) {     return orTree(cfs, 0, cfs.length - 1); }
  说明:  allOf => 所有的CompletableFuture都执行完后执行计算。  anyOf => 任意一个CompletableFuture执行完后就会执行计算
  示例:  allOf方法测试  public class AllOfTest {   public static void main(String[] args) throws ExecutionException, InterruptedException {       CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {           System.out.println("hello");           return null;       });       CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {           System.out.println("world"); return null;       });       CompletableFuture result = CompletableFuture.allOf(future1, future2);       System.out.println(result.get());   } }
  allOf方法没有返回值,适合没有返回值并且需要前面所有任务执行完毕才能执行后续任务的应用场景  anyOf方法测试  public class AnyOfTest {   private static Random random = new Random();   public static void main(String[] args) throws ExecutionException, InterruptedException {       CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {           randomSleep();           System.out.println("hello");           return "hello";});       CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {           randomSleep();           System.out.println("world");           return "world";       });       CompletableFuture result = CompletableFuture.anyOf(future1, future2);       System.out.println(result.get());  }      private static void randomSleep() {       try {           Thread.sleep(random.nextInt(10));       } catch (InterruptedException e) {           e.printStackTrace();       }   } }
  两个线程都会将结果打印出来,但是get方法只会返回最先完成任务的结果。该方法比较适合只要有一个返回值就可以继续执行其他任务的应用场景  注意点
  很多方法都提供了异步实现【带async后缀】,但是需小心谨慎使用这些异步方法,因为异步意味着存在上下文切换,可能性能不一定比同步好。如果需要使用异步的方法, 先做测试 ,用测试数据说话!!! CompletableFuture的应用场景
  存在IO密集型的任务可以选择CompletableFuture,IO部分交由另外一个线程去执行。Logback、Log4j2异步日志记录的实现原理就是新起了一个线程去执行IO操作,这部分可以以CompletableFuture.runAsync(()->{ioOperation();})的方式去调用。如果是CPU密集型就不推荐使用了推荐使用并行流  优化空间
  supplyAsync执行任务底层实现:  public static  CompletableFuture supplyAsync(Supplier supplier) {     return asyncSupplyStage(asyncPool, supplier); } static  CompletableFuture asyncSupplyStage(Executor e, Supplier f) {     if (f == null) throw new NullPointerException();     CompletableFuture d = new CompletableFuture();     e.execute(new AsyncSupply(d, f));     return d; }
  底层调用的是线程池去执行任务,而CompletableFuture中默认线程池为ForkJoinPool  private static final Executor asyncPool = useCommonPool ?         ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
  ForkJoinPool线程池的大小取决于CPU的核数。CPU密集型任务线程池大小配置为CPU核心数就可以了,但是IO密集型,线程池的大小由CPU数量 * CPU利用率 * (1 + 线程等待时间/线程CPU时间)确定。而CompletableFuture的应用场景就是IO密集型任务,因此默认的ForkJoinPool一般无法达到最佳性能,我们需自己根据业务创建线程池
汪涵何炅联袂还原历史人物,百炼成钢能否征服年轻人的心?大家都知道汪涵和何炅都是湖南卫视著名的电视节目主持人,因分别主持天天向上和快乐大本营两档人气很高的综艺节目,因此在年轻观众心中拥有很高的知名度和影响力。何炅(左)与汪涵(右)而如果脾气大态度嚣张?余文乐当众发飙辱骂工作人员,被网友嘲素质太差最近不少明星开始蠢蠢欲动,离开了家里的舒适圈,外出吃饭聚餐。余文乐就在近日被记者拍到,和友人外出吃饭的照片,但是据现场人员透露,余文乐因为停车不顺火气大,还对着工作人员大喊大骂。从这座低调的广西城市,其实有超多闻名全国的网红名片提起广西,你会想到哪里呢?要说广西人气最高的城市,应该就非桂林莫属了。俗话说桂林山水甲天下,桂林是闻名世界的旅游目的地,许多人都曾经或者梦想着到桂林玩一趟。桂林其次,作为广西省城以一口气看6部高甜腐剧,看完我对泰国人口产生担忧把近几年一部分火的泰腐剧拿出来都撸了一遍,看完之后我对泰国人口产生了深深地忧虑。因为国人对于泰语的接受无能,所以泰剧能够出圈的并不多,我看的最多的就是小水主演的几部剧,尤其是火之迷新疆这个城市被国家命名,全国示范!全疆唯一入选的城市喜大普奔!又一振奋人心的消息传来!乌鲁木齐又被国家委以重任,又要火了!蜜之番新疆吐鲁番特产10色10味葡萄干23。8购买4月13日乌鲁木齐市正式被国家民委授予全国民族团结大事件!2020乌鲁木齐要全面开挂!其他城市要羡慕死了今天小编给大家带来了一大拨好消息来啦!与你有关赶紧看看吧加装电梯乌鲁木齐市今年将为既有多层建筑加装电梯100部资料图片4月17日记者从乌鲁木齐市建设局(人防办)了解到今年乌鲁木齐市14。59万起,后排坐得下大个子,科技配置丰富,威朗ProGS实测作为一款颜值颇高的紧凑型运动轿车,我一直在关注威朗ProGS的相关信息。而今天终于有机会对这款车进行全方位近距离的体验,所以趁着这个机会,我将自己的体验情况给大家汇报一下。首先从车主打动力性的紧凑型SUV,东风风神AX7马赫版,价格最高不到13万紧凑型SUV一直是国产品牌投入重兵,竞争激烈的主战场,近年来也先后诞生了诸如哈弗H6,长城CS75PLUS等爆款车型。似乎得紧凑型SUV者得天下对自主品牌来说,是一个颠扑不破的真理江苏的省道比国道好?去滨海县,射阳县看看,就会理解这句话9月21日从滨海骑车去射阳县城,第2天下午骑回家,深深体会到偏海边的射阳县现在交通状况太发达了海边有射阳港。县城离盐城飞机场只有44公里。去年通车的青盐高铁有射阳站。沈海沿海高速穿常泰大桥工程进度快,泰州彩虹路美,兴化市大工程一个又一个2020年5月19日,一人一车,环山东半岛。渤海湾骑行第一天。早6时从常州市天宁区出发,经长江北路上圩塘汽渡过长江,沿高港大道,东风快速路辅路经泰渔路转上231省道,一直向北骑,下长江两岸去探班,常泰公铁大桥工程已正式开工,世界造桥史上新突破人人都说江苏是经济大省,交通四通八达,殊不知江苏的苏北地区因长江阻断,目前只有西南方向的南京长江大桥可以过火车,几十年来苏北人民想坐火车到苏南必须绕道南京前往苏南,十分不方便,只有
海信液晶电视质量究竟怎么样?谁能给点建议?不怎么样,刚过质保就黑屏,维修工人还说不一定能修,感觉就是买了个垃圾。和以前质量差远了,我家这是第三台了,第一台用了七八年,第二台四年就坏了,第三台第二年就坏了,包修后又过了两年又健康码到底是谁发明的呢?健康码在疫情防控中的作用可谓功不可没,它的工作原理是基于定位,既包括基站定位卫星定位,也包括WIFI定位,即便关机或拔卡都不影响手机定位。在手机定位的基础上,通过消费记录乘车记录飞小米11Lite5GNE新机即将登陆印度市场小米11系列已经拥有相当庞大的阵容,其中包括了小米11标准版11Pro11Ultra和小米11X11Pro等机型。不过几周后,该公司还将带来小米11T与Lite衍生版本。近日有报道玩游戏不喜欢卡,最好散热性能好,有符合要求的手机吗?我推荐最新的红魔6spro,自带散热风扇,肯定比没有风扇的手机要好的多。红魔出这么多代了也是比较成熟了。别的手机不管你内置什么散热材料,一个道理都是要通过表面散热出去的,还有什么液微信和QQ,你比较喜欢用哪个?QQ,一般只在pc端用,沿用了以前的习惯,现在也多用于工作上的沟通。微信主要是朋友圈,手机上使用率非常高。但是现在越来越多的人醒来第一件事已经不是微信或qq了,而是打开头条,看看粉普通人适不适合使用5G手机?5G手机广泛使用于哪些人?现在都2021年9月了,还问普通人适不适合使用5G手机,你现在去购买手机,看看市面上在售的手机里面,5G手机是不是成为了主流?当初在5G上面最不积极的苹果,它在去年推出的iPhon最新电脑为什么用ghost无法安装系统?安装版正常?为什么?因为硬盘有隐藏分区,通过PE把隐藏分区删除就可以正常Ghost。由于最新的电脑基本都是采用的UEF启动模式,硬盘分区一般都是GPT分区,系统安装模式一般都是UEFI模式,和传统BI你人生中的第一部手机是什么牌子的?多大时候买的?第一部手机2016年买的三星note5,4880元,那时候18岁,刚出来打工不到三个月,那时候一个月才两千五,我人生的第一部手机是熊猫牌比较小是白色翻盖,黑白屏的。是什么型号就忘记助听器为什么要订做耳模,有什么用处?助听器耳模是为耳背式助听器特别定制的耳塞,它在耳聋听力补偿中具有十分重要的作用1。定制比较好的耳模可提高助听效果30左右。2。防止并降低啸叫及杂音,消除声反馈啸叫。3。固定助听器。如何清洁助听器耳模?你好,可以收藏一下几个要点1每天用干燥柔软的布料把耳模擦净,并除去声孔内的污物。2每周用肥皂水洗涤一次,去掉油污。切记不可用酒精擦洗,因为酒精可溶解耳模材料,用酒精擦洗后耳模表面会把钱放支付宝的余额宝好,还是微信零钱通好?这是有钱人的烦恼,我这三位数的余额放哪都无所谓支付宝的余额宝出来后我就一直用着,刚开始确实收益高,一万每天能给一元多,后来又出了余利宝比余额宝收益多一点,现在基本上余额宝和余额宝差