异步编程CompletableFuture Api实践

简介: 本片文章主要是介绍异步编程CompletableFuture Api的实践

概述

在Java编程中,经常需要异步执行某个任务,一般继承Thread类或实现Runnable接口的方法来异步执行任务,除了这两种方法外,还可实现Callable来实现,在使用Callable的同时一般都会使用Future来配合获取执行结果,这几种方式使用起来或多或少存在不足,在jdk1.8中,提供了一个异步处理任务的工具CompletableFuture,接下来就通过实际代码体验CompletableFuture的使用。

创建异步线程任务

根据supplier创建CompletableFuture任务

ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> System.out.println("hello CompletableFuture1"), executor);
        // supplyAsync的使用
CompletableFuture<String> future = CompletableFuture
                .supplyAsync(() -> {
                    System.out.print("hello ");
                    return "CompletableFuture2";
                }, executor);

        // 阻塞等待,runAsync 的future 无返回值,输出null
        System.out.println(completableFuture.join());
        // 阻塞等待
        String name = future.join();
        System.out.println(name);
        executor.shutdown();
--------输出结果--------
hello CompletableFuture1
null
hello CompletableFuture2

线程串行执行

任务完成则运行action,不关心上一个任务的结果,无返回值

CompletableFuture<Void> future = CompletableFuture
        .supplyAsync(() -> "hello siting", executor)
        .thenRunAsync(() -> System.out.println("OK"), executor);
executor.shutdown();
--------输出结果--------
OK

任务完成则运行fn,依赖上一个任务的结果,有返回值

ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> "hello world", executor)
        .thenApplyAsync(data -> {
            System.out.println(data); return "OK";
        }, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello world
OK

thenCompose - 任务完成则运行fn,依赖上一个任务的结果,有返回值

//第一个异步任务,常量任务
CompletableFuture<String> f = CompletableFuture.completedFuture("OK");
//第二个异步任务
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> "hello world", executor)
        .thenComposeAsync(data -> {
            System.out.println(data); return f; //使用第一个任务作为返回
        }, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello world
OK

线程并行执行

两个CompletableFuture并行执行完,然后执行action,不依赖上两个任务的结果,无返回值

//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // () -> System.out.println("OK") 是第三个任务
        .runAfterBothAsync(first, () -> System.out.println("OK"), executor);
executor.shutdown();
--------输出结果--------
OK

两个CompletableFuture并行执行完,然后执行action,依赖上两个任务的结果,无返回值

//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // (w, s) -> System.out.println(s) 是第三个任务
        .thenAcceptBothAsync(first, (s, w) -> System.out.println(s), executor);
executor.shutdown();
--------输出结果--------
hello siting

两个CompletableFuture并行执行完,然后执行fn,依赖上两个任务的结果,有返回值

//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // (w, s) -> System.out.println(s) 是第三个任务
        .thenCombineAsync(first, (s, w) -> {
            System.out.println(s);
            return "OK";
        }, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello siting
OK

线程并行执行(二者选其最快)

线程并行执行,谁先执行完则谁触发下一任务

上一个任务或者other任务完成, 运行action,不依赖前一任务的结果,无返回值

// 第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
    try{ Thread.sleep(1000); }catch (Exception e){}
    System.out.println("hello world");
    return "hello world";
});
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
        // 第二个异步任务
        .supplyAsync(() ->{
            System.out.println("hello siting");
            return "hello siting";
        } , executor)
        // () ->  System.out.println("OK") 是第三个任务
        .runAfterEitherAsync(first, () ->  System.out.println("OK") , executor);
executor.shutdown();
--------输出结果--------
hello siting
OK

上一个任务或者other任务完成, 运行action,依赖最先完成任务的结果,无返回值

// 第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
    try{ Thread.sleep(1000);  }catch (Exception e){}
    return "hello world";
});
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
        // 第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // data ->  System.out.println(data) 是第三个任务
        .acceptEitherAsync(first, data ->  System.out.println(data) , executor);
executor.shutdown();
--------输出结果--------
hello siting

上一个任务或者other任务完成, 运行fn,依赖最先完成任务的结果,有返回值

//第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
    try{ Thread.sleep(1000);  }catch (Exception e){}
    return "hello world";
});
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
        //第二个异步任务
        .supplyAsync(() -> "hello siting", executor)
        // data ->  System.out.println(data) 是第三个任务
        .applyToEitherAsync(first, data ->  {
            System.out.println(data);
            return "OK";
        } , executor);
System.out.println(future);
executor.shutdown();
--------输出结果--------
hello siting
OK

处理任务结果或者异常

exceptionally-处理异常:如果之前的处理环节有异常问题,则会触发exceptionally的调用相当于 try...catch

CompletableFuture<Integer> first = CompletableFuture
        .supplyAsync(() -> {
            if (true) {
                throw new RuntimeException("main error!");
            }
            return "hello world";
        })
        .thenApply(data -> 1)
        .exceptionally(e -> {
            e.printStackTrace(); // 异常捕捉处理,前面两个处理环节的日常都能捕获
            return 0;
        });

handle-任务完成或者异常时运行fn,返回值为fn的返回

CompletableFuture<Integer> first = CompletableFuture
        .supplyAsync(() -> {
            if (true) { throw new RuntimeException("main error!"); }
            return "hello world";
        })
        .thenApply(data -> 1)
        .handleAsync((data,e) -> {
            e.printStackTrace(); // 异常捕捉处理
            return data;
        });
System.out.println(first.join());
--------输出结果--------
java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
    ... 5 more
null

whenComplete-任务完成或者异常时运行action,有返回值

  • whenComplete与handle的区别在于,它不参与返回结果的处理,把它当成监听器即可
  • 即使异常被处理,在CompletableFuture外层,异常也会再次复现
  • 使用whenCompleteAsync时,返回结果则需要考虑多线程操作问题,毕竟会出现两个线程同时操作一个结果
CompletableFuture<AtomicBoolean> first = CompletableFuture
        .supplyAsync(() -> {
            if (true) {  throw new RuntimeException("main error!"); }
            return "hello world";
        })
        .thenApply(data -> new AtomicBoolean(false))
        .whenCompleteAsync((data,e) -> {
            //异常捕捉处理, 但是异常还是会在外层复现
            System.out.println(e.getMessage());
        });
first.join();
--------输出结果--------
java.lang.RuntimeException: main error!
Exception in thread "main" java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
    ... 5 more

多个任务的简单组合

 CompletableFuture<Void> future = CompletableFuture
        .allOf(CompletableFuture.completedFuture("A"),
                CompletableFuture.completedFuture("B"));
//全部任务都需要执行完
future.join();
CompletableFuture<Object> future2 = CompletableFuture
        .anyOf(CompletableFuture.completedFuture("C"),
                CompletableFuture.completedFuture("D"));
//其中一个任务行完即可
future2.join();

取消执行线程任务

CompletableFuture<Integer> future = CompletableFuture
        .supplyAsync(() -> {
            try { Thread.sleep(1000);  } catch (Exception e) { }
            return "hello world";
        })
        .thenApply(data -> 1);

System.out.println("任务取消前:" + future.isCancelled());
// 如果任务未完成,则返回异常,需要对使用exceptionally,handle 对结果处理
future.cancel(true);
System.out.println("任务取消后:" + future.isCancelled());
future = future.exceptionally(e -> {
    e.printStackTrace();
    return 0;
});
System.out.println(future.join());
--------输出结果--------
任务取消前:false
任务取消后:true
java.util.concurrent.CancellationException
    at java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2276)
    at Test.main(Test.java:25)
相关文章
|
2月前
|
JavaScript 前端开发 API
深入浅出:Vue 3 Composition API 的魅力与实践
【2月更文挑战第13天】 本文将探索 Vue 3 的核心特性之一——Composition API。通过对比 Options API,本文旨在揭示 Composition API 如何提高代码的组织性和可复用性,并通过实际案例展示其在现代前端开发中的应用。不同于传统的技术文章摘要,我们将通过一个具体的开发场景,引领读者步入 Composition API 的世界,展现它如何优雅地解决复杂组件逻辑的管理问题,从而激发读者探索和运用 Vue 3 新特性的热情。
25 1
|
3月前
|
数据采集 监控 算法
利用大数据和API优化电商决策:商品性能分析实践
在数据驱动的电子商务时代,大数据分析已成为企业提升运营效率、增强市场竞争力的关键工具。通过精确收集和分析商品性能数据,企业能够洞察市场趋势,实现库存优化,提升顾客满意度,并显著增加销售额。本文将探讨如何通过API收集商品数据,并将这些数据转化为对电商平台有价值的洞察。
|
3月前
|
人工智能 NoSQL Serverless
基于函数计算3.0 Stable Diffusion Serverless API 的AI艺术字头像生成应用搭建与实践的报告
本文主要分享了自己基于函数计算3.0 Stable Diffusion Serverless API 的AI艺术字头像生成应用搭建与实践的报告
477 6
基于函数计算3.0 Stable Diffusion Serverless API 的AI艺术字头像生成应用搭建与实践的报告
|
4月前
|
存储 缓存 测试技术
4个所有开发人员都应该知道的关键API缓存实践
4个所有开发人员都应该知道的关键API缓存实践
|
3月前
|
安全 前端开发 API
深入理解与实践GraphQL:构建高效、灵活的API
在本文中,我们将探索GraphQL这一强大的API查询语言及其运行原理。不同于传统的RESTful API设计,GraphQL提供了一种更加高效、灵活的方式来交互数据。通过实例和比较,本文旨在揭示GraphQL如何使前端和后端开发更加紧密协作,同时减少数据传输的冗余。我们将从GraphQL的基本概念入手,深入到查询(Queries)、变更(Mutations)和订阅(Subscriptions)的实现,最后探讨如何在实际项目中部署和优化GraphQL服务。此外,本文还将简要介绍如何利用现有的GraphQL工具和库来加速开发过程。
|
2天前
|
缓存 负载均衡 API
微服务架构下的API网关性能优化实践
【5月更文挑战第10天】在微服务架构中,API网关作为前端和后端服务之间的关键枢纽,其性能直接影响到整个系统的响应速度和稳定性。本文将探讨在高并发场景下,如何通过缓存策略、负载均衡、异步处理等技术手段对API网关进行性能优化,以确保用户体验和服务的可靠性。
|
5天前
|
存储 缓存 JavaScript
深入理解RESTful API设计原则与实践
【5月更文挑战第7天】在现代Web服务开发中,表述性状态传递(REST)是一种广泛采用的架构风格,用于构建可扩展的网络应用程序接口(APIs)。本文将探讨RESTful API的核心设计原则,并通过具体实例展示如何实现一个符合REST约束的后端服务。我们将讨论资源的识别、客户端-服务器通信模式、无状态性、以及统一接口的重要性,并探索如何使用当前的流行技术栈来实现这些概念。
|
6天前
|
JSON API 数据格式
淘宝商品评论数据获取:从API调用到应用实践
在电商的世界里,用户评论是洞察商品质量的一扇窗。淘宝,作为中国最大的在线购物平台,其海量的商品评论数据尤为宝贵。本文将带您走进淘宝商品评论数据的获取之旅,从API调用的基础知识到实际应用的代码示例,一探究竟。
|
23天前
|
消息中间件 缓存 算法
构建高效的后端API:优化方法与实践
随着互联网技术的迅速发展,构建高效的后端API已成为现代软件开发中的重要挑战。本文将探讨一些优化方法与实践,以帮助开发人员提高后端API的性能和可靠性。我们将讨论如何通过缓存、异步处理、数据库优化以及代码优化等方式来提升后端API的响应速度和吞吐量,从而为用户提供更好的体验。
|
2月前
|
XML JSON 安全
谈谈你对RESTful API设计的理解和实践。
RESTful API是基于HTTP协议的接口设计,通过URI标识资源,利用GET、POST、PUT、DELETE等方法操作资源。设计注重无状态、一致性、分层、错误处理、版本控制、文档、安全和测试,确保易用、可扩展和安全。例如,`/users/{id}`用于用户管理,使用JSON或XML交换数据,提升系统互操作性和可维护性。
18 4