Java8中引入了不少新的特性,如:
- lambda表达式:Lambda表达式允许在代码中直接定义匿名函数,使得Java对函数式编程的支持更加完善。它极大地简化了代码,使得开发者能够编写出更简洁、更灵活的代码。
- Stream API:Stream API为处理数据提供了一种高效且易于使用的方式。通过使用Stream API,开发者可以编写出更简洁、更易于阅读的代码来处理集合数据。它提供了诸如filter、map、sorted等常用的方法,使得数据操作更加直观和方便。
- Date/Time API:Java 8引入了新的日期和时间API,替代了之前复杂且易出错的java.util.Date和java.util.Calendar类。新的API提供了更加直观和灵活的方式来处理日期和时间。
- 接口的默认方法和静态方法:在Java 8中,接口可以包含默认方法和静态方法。默认方法允许在接口中定义方法的具体实现,而静态方法与类中的静态方法类似,可以在接口中使用static关键字定义。
- 函数式接口:Java 8引入了函数式接口的概念,这是一个只包含一个抽象方法的接口。Lambda表达式可以很容易地与函数式接口结合使用,从而支持函数式编程。
- 方法引用:方法引用是Lambda表达式的一个简化形式,它允许我们直接引用已存在的方法或构造器。
- Optional容器:Optional是一个可以为null的容器对象。它的引入旨在减少空指针异常的发生,使得代码更加健壮。
- CompletableFuture
今天,我们就来看看这个CompletableFuture,它是什么、怎么用、以及使用过程中需要注意什么。
是什么?(CompletableFuture,Future,CompletionStage,Function,Consumer,Supplier...)
CompletableFuture是Java 8中引入的一个功能强大的类,它位于包JUC(java.util.concurrent)下,是Java Future和CompletionStage API的扩展,专为异步编程而设计。它允许我们将任务运行在与主线程分离的其他线程中,并通过回调在主线程中得到异步任务执行的状态,包括是否完成、是否异常等信息。这种设计使得主线程不会阻塞或等待任务的完成,从而可以并行执行其他任务,极大地提高了程序的性能。
CompletableFuture的主要用途在于异步编程,特别是在需要执行耗时的操作(如I/O操作)时,可以将其放在后台线程中执行,同时主线程可以继续执行其他任务。一旦后台任务完成,主线程可以通过回调机制获取结果或处理异常情况(基于观察者设计模式)。
/**
* A {@link Future} that may be explicitly completed (setting its
* value and status), and may be used as a {@link CompletionStage},
* supporting dependent functions and actions that trigger upon its
* completion.
*
* <p>When two or more threads attempt to
* {@link #complete complete},
* {@link #completeExceptionally completeExceptionally}, or
* {@link #cancel cancel}
* a CompletableFuture, only one of them succeeds.
*
* <p>In addition to these and related methods for directly
* manipulating status and results, CompletableFuture implements
* interface {@link CompletionStage} with the following policies: <ul>
*
* <li>Actions supplied for dependent completions of
* <em>non-async</em> methods may be performed by the thread that
* completes the current CompletableFuture, or by any other caller of
* a completion method.</li>
*
* <li>All <em>async</em> methods without an explicit Executor
* argument are performed using the {@link ForkJoinPool#commonPool()}
* (unless it does not support a parallelism level of at least two, in
* which case, a new Thread is created to run each task). To simplify
* monitoring, debugging, and tracking, all generated asynchronous
* tasks are instances of the marker interface {@link
* AsynchronousCompletionTask}. </li>
*
* <li>All CompletionStage methods are implemented independently of
* other public methods, so the behavior of one method is not impacted
* by overrides of others in subclasses. </li> </ul>
*
* <p>CompletableFuture also implements {@link Future} with the following
* policies: <ul>
*
* <li>Since (unlike {@link FutureTask}) this class has no direct
* control over the computation that causes it to be completed,
* cancellation is treated as just another form of exceptional
* completion. Method {@link #cancel cancel} has the same effect as
* {@code completeExceptionally(new CancellationException())}. Method
* {@link #isCompletedExceptionally} can be used to determine if a
* CompletableFuture completed in any exceptional fashion.</li>
*
* <li>In case of exceptional completion with a CompletionException,
* methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
* {@link ExecutionException} with the same cause as held in the
* corresponding CompletionException. To simplify usage in most
* contexts, this class also defines methods {@link #join()} and
* {@link #getNow} that instead throw the CompletionException directly
* in these cases.</li> </ul>
*
* @author Doug Lea
* @since 1.8
*/
public class CompletableFuture<T> implements Future<T>, CompletionStage<T>
从定义中,我们可以看到,CompletableFuture同时实现了Future接口和CompletionStage。
Future接口中定义了如下几个方法:

如:通过get()方法可以获取异步任务的结果,isDone()可以判断任务是否已完成。
CompletionStage接口在Java中代表一个异步计算的可能阶段。它允许开发者定义当一个或多个CompletionStage完成时要执行的操作或计算的值。这个接口特别强大,因为它提供了多种方式来组合和编排异步任务。

CompletionStage接口内部的方法主要由几个关键单词组合而成,如apply、accept、run、then、both、either和async

本文介绍了Java 8引入的CompletableFuture,它是Java Future和CompletionStage API的扩展,用于异步编程。文中阐述了其概念、用途,详细讲解了创建异步任务、异步回调、组合处理等方法的使用,还提醒使用时要注意线程池选择、异常处理和结果获取等问题。
最低0.47元/天 解锁文章
3241

被折叠的 条评论
为什么被折叠?



