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

代替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系gt车衣施工效果展示,专业的隐形车衣,用心保护你的爱车改造车型BMW宝马6系gt车身颜色贝尔尼纳灰改造产品XPELLUXPLUS隐形车衣车型介绍GT是GranTurismo的缩写,指适合长距离高速行驶的豪华轿跑车,GT车型集大马力高性保时捷911Carrera威固车窗膜改造是传奇,也是信仰改造车型保时捷911Carrera车型颜色黑玉色改造产品威固隔热窗膜顶级前档vk70侧后k28车型介绍Modelintroduction保时捷911是由德国斯图加特市的保时捷公司所坦克500正式亮相,陆巡将迎来大敌坦克500是长城汽车子品牌坦克旗下的又一硬派SUV车型,之前网上炒的火热的坦克600官方宣布正式更名为坦克500,将会在2天后的成都车展上亮相。坦克自今年4月份上海车展期间宣布成为成都车展重磅新车,坦克霸气不减,五菱版QQ尴尬撞脸成都国际汽车站今天在中国西部博览城正式开启。本次车展期间各大车企将接连发布各种新车。首先盘点一下本次车展关注度比较高的十款车型吧。坦克500坦克汽车自4月份上海车展之后就壮志满满,奥迪A6隐形车衣装贴案例神车还要神衣加持奥迪A6L,C级车的代表,国企政府的官配,也因为销量与保有量被称为神车。官方说法是比较低调踏实有内涵,虽然豪华感不如奔驰宝马,但是具备百看不厌的高颜值外观,激情澎湃的车身动力,简单电脑卡顿问题怎么办,教你处理现在的每个家庭几乎都必备有一台电脑。而现在的大学生基本上都是人手备有一台手提电脑方便学习,至于计算机系的更是需要一台电脑了,毕竟是学习计算机的都是需要一台电脑。那么这样一来,使用电魅族新机CPU主频2。95GHz,应为魅族18Pro换芯版小编了解到,魅族18入网型号为M181Q,魅族18Pro入网型号为M191Q。考虑到入网新机的参数,这两款手机应为搭载骁龙888Plus处理器的魅族18系列换芯版。配置方面,这款手荣耀手表GS3官方实拍图公布这质感商务风拉满荣耀手表GS3融合传统腕表极简风格,配以3D曲面表镜,提供了竞速先锋环球远航流光经典三款外观设计。其中,流光经典设计以暖金为主色调,官方称之在时光的快慢交替中,诠释出绅士般的优雅与微软Windows11将于10月5日上市Win10PC免费升级Windows11是Windows10发布6年后的首个重大操作系统升级,其成功上市可能会进一步确保Window特许经营权的未来,也将使微软的其他业务部门受益,如Azure和Offi小米新机素颜照公布!157g刷新小米最轻5G手机纪录这款新机的整体造型与小米11青春版相似,可能是传闻中的小米CC11。该机最大的看点就是轻薄设计,其重量只有157g,比小米11青春版还要轻2g,是迄今为止最轻的小米5G手机。此外,iPhone13将支持低轨道卫星通信可以没有4G5G网络通信iPhone13系列将配备能够连接到LEO的硬件。如果启用了相关的软件功能,iPhone13用户可在不需要4G或5G蜂窝网络连接的情况下拨打电话和发送消息。当然,这个系统并非只有硬
王卫,创立顺丰快递,从穷小子变身总裁曾被黑道追杀,出门带保镖,拒绝两次见马云,从穷小子变身总裁,这个人就是顺丰快递总裁王卫。王卫行事低调,高中毕业的他,充满了传奇色彩。王卫在2021年中国富人榜上,以2381亿元,排比DownloadStation好用100倍!NAS神器Docker设置教程很多NAS玩家都很重视下载这个功能,一些小白刚上手NAS的时候,觉得自带的DownloadStation真的太好用了。但是时间一长后就发现,怎么这个链接下载不了,那个链接没有速度,曹德旺先生,福耀集团创始人,称霸世界的汽车玻璃大王曹德旺先生,福耀集团创始人,世界公认的汽车玻璃大王。曹德旺1946年出生在上海,他的曾祖父是福建福清首富。他的父亲是上海永安百货的老板,他的母亲是地主的千金。1947年,国民党政权李振国先生,隆基创始人,厚积薄发,一辈子只干光伏李振国先生,1968年5月出生在河南许昌的小村庄。他的父亲是当时村里唯一的大学生,所以对李振国的学习特别严格,李振国十二岁离开家乡,之后到西宁,1986年李振国不负众望,考入兰州大孙宏斌,融创地产创始人,出狱后的商界枭雄孙宏斌,融创中国创始人,1963年出生于山西运城。童年时期,家境贫寒,兄弟四人,他排行老大,他从小就深知要通过知识改变命运。1978年,15岁的孙宏斌一边干农活一边看书学习,在恢复电费太贵不敢开空调?这样开空调更省电!从此实现空调自由冰西瓜和空调简直是夏季标配啊!但看到蹭蹭涨的电费,默默拿起空调遥控器关掉空调打开风扇那么夏季如何使用空调才最省电呢?记住下面这几点就好了!1。温度不是越低越好空调的温度设定的越低耗黑暗在漫步谷歌Chrome暗黑模式终于全面到来根据外媒techradar报道,谷歌正在为其浏览器和ChromeOS操作系统的桌面版本开发一种暗黑模式,而这种即将全面到来!几个月来,在Android上激活Chrome的黑暗模式可纯SSD存储的NASbook到底是个啥?威联通TBS453DX上手体验创作前言我们回头查看SSD的发展史,发现可以简单看成存储密度的叠加史,从原先的SLCMLCTLC再到如今的QLC,从最开始的平面NAND到3D32层48层72层以及96层NAND,新手群?老手威?群晖VS威联通,一篇打尽所有不同创作说明入NAS坑也几年了,玩过的产品有群晖威联通华芸西部数据MyCloud以及Drobo等,也是看着NAS从几年前的冷门变成现在的渐热。在之前,国内NAS市场是群晖一家独大,威联李想,理想汽车和汽车之家创始人,高中生也可以创业成功李想,理想汽车和汽车之家创始人,1981年10月出生于石家庄。他从小被姥姥带大,父亲是剧团导演,母亲是学校老师,家庭并不富裕。高中时代的李想喜爱电脑,成为IT行业的顶级写手,他的文最便宜的万兆体验威联通TS532XNAS评测玩NAS也几年了,一直想体验一下万兆的速度,但是万兆NAS的价格一直太贵,所以搁置了许久。之前看到威联通推出了TS532X,2000的价格让人有点心动。但是万兆的配件太贵,所以一直