Java 9 CompletableFuture API Improvements – Java 9可完成的未来API改进

最后修改: 2017年 3月 13日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

Java 9 comes with some changes to the CompletableFuture class. Such changes were introduced as part of JEP 266 in order to address common complaints and suggestions since its introduction in JDK 8, more specifically, support for delays and timeouts, better support for subclassing and a few utility methods.

Java 9对CompletableFuture类进行了一些修改。这样的变化是作为JEP 266的一部分引入的,目的是为了解决自JDK 8中引入该类后的普遍抱怨和建议,更具体地说,就是支持延迟和超时,更好地支持子类和一些实用方法。

Code-wise, the API comes with eight new methods and five new static methods. To enable such additions, approximately, 1500 out of 2400 lines of code were changed (as per Open JDK).

从代码上看,该API有八个新方法和五个新的静态方法。为了实现这些新增功能,在2400行代码中大约有1500行被修改(根据Open JDK)。

2. Instance API Additions

2.实例API的增加

As mentioned, the instance API comes with eight new additions, they are:

如前所述,该实例的API带有八个新的内容,它们是。

  1. Executor defaultExecutor()
  2. CompletableFuture<U> newIncompleteFuture()
  3. CompletableFuture<T> copy()
  4. CompletionStage<T> minimalCompletionStage()
  5. CompletableFuture<T> completeAsync(Supplier<? extends T> supplier, Executor executor)
  6. CompletableFuture<T> completeAsync(Supplier<? extends T> supplier)
  7. CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
  8. CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)

2.1. Method defaultExecutor()

2.1.方法defaultExecutor()

Signature: Executor defaultExecutor()

签名Executor defaultExecutor()

Returns the default Executor used for async methods that do not specify an Executor.

返回默认的Executor,用于没有指定Executor的异步方法。

new CompletableFuture().defaultExecutor()

This can be overridden by subclasses returning an executor providing, at least, one independent thread.

这一点可以被返回执行器的子类所重写,执行器至少提供一个独立的线程。

2.2. Method newIncompleteFuture()

2.2.方法newIncompleteFuture()

Signature: CompletableFuture<U> newIncompleteFuture()

签名CompletableFuture<U> newIncompleteFuture()

The newIncompleteFuture, also known as the “virtual constructor”, is used to get a new completable future instance of the same type.

newIncompleteFuture,也被称为 “虚拟构造函数”,用于获得一个相同类型的新的可完成未来实例。

new CompletableFuture().newIncompleteFuture()

This method is especially useful when subclassing CompletableFuture, mainly because it is used internally in almost all methods returning a new CompletionStage, allowing subclasses to control what subtype gets returned by such methods.

这个方法在子类化CompletableFuture时特别有用,主要是因为它在内部被用于几乎所有返回新CompletionStage的方法,允许子类控制此类方法返回的子类型。

2.3. Method copy()

2.3.方法copy()

Signature: CompletableFuture<T> copy()

签名CompletableFuture<T> copy()

This method returns a new CompletableFuture which:

该方法返回一个新的CompletableFuture,它。

  • When this gets completed normally, the new one gets completed normally also
  • When this gets completed exceptionally with exception X, the new one is also completed exceptionally with a CompletionException with X as cause
new CompletableFuture().copy()

This method may be useful as a form of “defensive copying”, to prevent clients from completing, while still being able to arrange dependent actions on a specific instance of CompletableFuture.

这个方法作为一种 “防御性复制 “的形式可能很有用,可以防止客户完成,同时仍然能够在CompletableFuture的特定实例上安排依赖性操作。

2.4. Method minimalCompletionStage()

2.4.方法minimalCompletionStage()

Signature: CompletionStage<T> minimalCompletionStage()

签名CompletionStage<T> minimalCompletionStage()

This method returns a new CompletionStage which behaves in the exact same way as described by the copy method, however, such new instance throws UnsupportedOperationException in every attempt to retrieve or set the resolved value.

该方法返回一个新的CompletionStage,其行为方式与复制方法所描述的完全相同,但是,这样的新实例在每次试图检索或设置解析值时都会抛出UnsupportedOperationException

new CompletableFuture().minimalCompletionStage()

A new CompletableFuture with all methods available can be retrieved by using the toCompletableFuture method available on the CompletionStage API.

一个具有所有可用方法的新的CompletableFuture可以通过使用toCompletableFuture方法来检索。

2.5. Methods completeAsync()

2.5.方法 completeAsync()

The completeAsync method should be used to complete the CompletableFuture asynchronously using the value given by the Supplier provided.

completeAsync方法应该被用来使用所提供的Supplier给出的值异步完成CompletableFuture

Signatures:

签名

CompletableFuture<T> completeAsync(Supplier<? extends T> supplier, Executor executor)
CompletableFuture<T> completeAsync(Supplier<? extends T> supplier)

The difference between this two overloaded methods is the existence of the second argument, where the Executor running the task can be specified. If none is provided, the default executor (returned by the defaultExecutor method) will be used.

这两个重载方法的区别在于第二个参数的存在,可以指定运行任务的Executor。如果没有提供,将使用默认的执行器(由defaultExecutor方法返回)。

2.6. Methods orTimeout()

2.6.方法orTimeout()

Signature: CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)

签名CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)

new CompletableFuture().orTimeout(1, TimeUnit.SECONDS)

Resolves the CompletableFuture exceptionally with TimeoutException, unless it is completed before the specified timeout.

TimeoutException异常地解决CompletableFuture,除非它在指定的超时前完成。

2.7. Method completeOnTimeout()

2.7.方法completeOnTimeout()

Signature: CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)

签名CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)

new CompletableFuture().completeOnTimeout(value, 1, TimeUnit.SECONDS)

Completes the CompletableFuture normally with the specified value unless it is completed before the specified timeout.

用指定的值正常完成CompletableFuture,除非它在指定的超时前完成。

3. Static API Additions

3.静态API的增加

Some utility methods were also added. They are:

还增加了一些实用方法。它们是

  1. Executor delayedExecutor(long delay, TimeUnit unit, Executor executor)
  2. Executor delayedExecutor(long delay, TimeUnit unit)
  3. <U> CompletionStage<U> completedStage(U value)
  4. <U> CompletionStage<U> failedStage(Throwable ex)
  5. <U> CompletableFuture<U> failedFuture(Throwable ex)

3.1. Methods delayedExecutor

3.1.方法delayedExecutor

Signatures:

签名

Executor delayedExecutor(long delay, TimeUnit unit, Executor executor)
Executor delayedExecutor(long delay, TimeUnit unit)

Returns a new Executor that submits a task to the given base executor after the given delay (or no delay if non-positive). Each delay commences upon invocation of the returned executor’s execute method. If no executor is specified the default executor (ForkJoinPool.commonPool()) will be used.

返回一个新的Executor,在给定的延迟(如果不是正数,则没有延迟)后,将任务提交给给定的基本执行器。每个延迟都从调用返回的执行器的执行方法开始。如果没有指定执行器,将使用默认执行器(ForkJoinPool.commonPool())。

3.2. Methods completedStage and failedStage

3.2.方法completedStagefailedStage

Signatures:

签名

<U> CompletionStage<U> completedStage(U value)
<U> CompletionStage<U> failedStage(Throwable ex)

This utility methods return already resolved CompletionStage instances, either completed normally with a value (completedStage) or completed exceptionally (failedStage) with the given exception.

该实用程序方法返回已经解决的CompletionStage实例,要么正常完成了一个值(completedStage),要么异常完成了(failedStage)并出现了给定的异常。

3.3. Method failedFuture

3.3.方法failedFuture

Signature: <U> CompletableFuture<U> failedFuture(Throwable ex)

签名<U> CompletableFuture<U> failedFuture(Throwable ex)/em>

The failedFuture method adds the ability to specify an already completed exceptionally CompleatebleFuture instance.

failedFuture方法增加了指定一个已经完成的例外CompleatebleFuture实例的能力。

4. Example Use Cases

4.用例

Within this section, one will show some examples on how to use some of the new API.

在本节中,我们将展示一些关于如何使用一些新的API的例子。

4.1. Delay

4.1.延迟

This example will show how to delay the completion of a CompletableFuture with a specific value by one second. That can be achieved by using the completeAsync method together with the delayedExecutor.

这个例子将展示如何将一个具有特定值的CompletableFuture延迟一秒完成。这可以通过使用completeAsync方法和delayedExecutor一起实现。

CompletableFuture<Object> future = new CompletableFuture<>();
future.completeAsync(() -> input, CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));

4.2. Complete With Value on Timeout

4.2.在超时的情况下完成价值

Another way to achieve a delayed result is to use the completeOnTimeout method. This example defines a CompletableFuture that will be resolved with a given input if it stays unresolved after 1 second.

另一种实现延迟结果的方法是使用completeOnTimeout方法。这个例子定义了一个CompletableFuture,如果它在1秒后仍未被解决,就会用给定的输入解决。

CompletableFuture<Object> future = new CompletableFuture<>();
future.completeOnTimeout(input, 1, TimeUnit.SECONDS);

4.3. Timeout

4.3.超时

Another possibility is timing out which resolves the future exceptionally with TimeoutException. For example, having the CompletableFuture timing out after 1 second given it is not completed before that.

另一种可能性是超时,它可以用TimeoutException来例外解决未来。例如,让CompletableFuture在1秒后超时,因为在此之前它没有完成。

CompletableFuture<Object> future = new CompletableFuture<>();
future.orTimeout(1, TimeUnit.SECONDS);

5. Conclusion

5.结论

In conclusion, Java 9 comes with several additions to the CompletableFuture API, it now has better support for subclassing, thanks to the newIncompleteFuture virtual constructor, it is possible to take control over the CompletionStage instances returned in most of the CompletionStage API.

总之,Java 9对CompletableFuture API进行了一些补充,它现在对子类有了更好的支持,由于有了newIncompleteFuture虚拟构造函数,它可以对大多数CompletionStage API中返回的CompletionStage实例进行控制。

It has, definitely, better support for delays and timeouts as shown previously. The utility methods added follow a sensible pattern, giving CompletableFuture a convenient way to specify resolved instances.

毫无疑问,它对延迟和超时有更好的支持,如前所述。添加的实用方法遵循一种合理的模式,给CompletableFuture一种方便的方式来指定已解决的实例。

The examples used in this article can be found in our GitHub repository.

本文中使用的例子可以在我们的GitHub 仓库中找到。