简述:背景

上面就是​​CompletionStage​​​接口中方法的使用实例,​​CompletableFuture​​​同样也同样实现了​​Future​​​,所以也同样可以使用​​get​​​进行阻塞获取值,总的来说,​​CompletableFuture​​使用起来还是比较爽的,看起来也比较优雅一点。

public class BasicFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(10);
Future<Integer> f = es.submit(() ->{
// 长时间的异步计算
// ……
// 然后返回结果
return 100;
});
// while(!f.isDone());
f.get();
}
}

虽然​​Future​​​以及相关使用方法提供了异步执行任务的能力,但是对于结果的获取却是很不方便,只能通过阻塞或者轮询的方式得到任务的结果。阻塞的方式显然和我们的异步编程的初衷相违背,轮询的方式又会耗费无谓的​​CPU​​资源,而且也不能及时地得到计算结果,为什么不能用观察者设计模式当计算结果完成及时通知监听者呢?

📌Google guava提供了通用的扩展Future:​​ListenableFuture​​​、​​SettableFuture​​​ 以及辅助类​​Futures​​等,方便异步编程。

final String name = ...;
inFlight.add(name);
ListenableFuture<Result> future = service.query(name);
future.addListener(new Runnable() {
public void run() {
processedCount.incrementAndGet();
inFlight.remove(name);
lastProcessed.set(name);
logger.info("Done with {0}", name);
}
}, executor);

作为正统的​​Java​​类库,是不是应该做点什么,加强一下自身库的功能呢?

在​​Java 8​​​中, 新增加了一个包含​​50​​​个方法左右的类: ​​CompletableFuture​​​,提供了非常强大的​​Future​​​的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合​​CompletableFuture​​的方法。

下面我们就看一看它的功能吧。

​CompletableFuture​​​类实现了​​CompletionStage​​​和​​Future​​接口,所以你还是可以像以前一样通过阻塞或者轮询的方式获得结果,尽管这种方式不推荐使用。

public T   get()
public T get(long timeout, TimeUnit unit)
public T getNow(T valueIfAbsent)
public T join()

​getNow​​​有点特殊,如果结果已经计算完则返回结果或者抛出异常,否则返回给定的​​valueIfAbsent​​​值。
​​​join​​​返回计算的结果或者抛出一个​​unchecked​​​异常(​​CompletionException​​​),它和​​get​​对抛出的异常的处理有些细微的区别,你可以运行下面的代码进行比较:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
int i = 1/0;
return 100;
});
//future.join();
future.get();

一. 创建​​CompletableFuture​​对象

​CompletableFuture.completedFuture​​​是一个静态辅助方法,用来返回一个已经计算好的​​CompletableFuture​​。

而以下四个静态方法用来为一段异步执行的代码创建​​CompletableFuture​​对象:

public static CompletableFuture<Void> runAsync(Runnable runnable);
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor);
public static CompletableFuture supplyAsync(Supplier supplier);
public static CompletableFuture supplyAsync(Supplier supplier, Executor executor);

下面的四个方法可以用来创建​​CompletableFuture​​​对象,其中以​​Async​​​结尾并且没有指定​​Executor​​​的方法会使用​​ForkJoinPool.commonPool()​​作为它的线程池执行异步代码。

​runAsync​​​方法也好理解,它以​​Runnable​​​函数式接口类型为参数,所以​​CompletableFuture​​的计算结果为空。

​supplyAsync​​​方法以​​Supplier​​​函数式接口类型为参数,​​CompletableFuture​​​的计算结果类型为​​U​​。

因为方法的参数类型都是函数式接口,所以可以使用​​lambda​​表达式实现异步任务。

ThreadPoolExecutor executor = new ThreadPoolExecutor(
5,
10,
10,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(100)
);
// 异步执行,返回值
Integer result = CompletableFuture.supplyAsync(() -> 12, executor).get(); // 12
// 异步执行,无返回值
CompletableFuture.runAsync(() -> System.out.println(12), executor); // 12

二. 计算完成时的处理

当​​CompletableFuture​​​的计算结果完成,或者抛出异常的时候,我们可以执行特定的​​Action​​。主要是下面的方法:

public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action);
public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action);
public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor);
public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn);

三. 转换

​CompletableFuture​​​可以作为​​monad​​​(单子)和​​functor​​​。由于回调风格的实现,我们不必因为等待一个计算完成而阻塞着调用线程,而是告诉​​CompletableFuture​​​当计算完成的时候请执行某个​​function​​​。而且我们还可以将这些操作串联起来,或者将​​CompletableFuture​​组合起来。

public  CompletableFuture   thenApply(Function<? super T,? extends U> fn);
public CompletableFuture thenApplyAsync(Function<? super T,? extends U> fn);
public CompletableFuture thenApplyAsync(Function<? super T,? extends U> fn, Executor executor);

这一组函数的功能是当原来的​​CompletableFuture​​​计算完后,将结果传递给函数​​fn​​​,将​​fn​​​的结果作为新的​​CompletableFuture​​​计算结果。因此它的功能相当于将​​CompletableFuture<T>​​​转换成​​CompletableFuture​​。

这三个函数的区别和上面介绍的一样,不以​​Async​​​结尾的方法由原来的线程计算,以​​Async​​​结尾的方法由默认的线程池​​ForkJoinPool.commonPool()​​​或者指定的线程池​​executor​​​运行。Java的​​CompletableFuture​​类总是遵循这样的原则,下面就不一一赘述了。

使用例子如下:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 100;
});
CompletableFuture<String> f = future.thenApplyAsync(i -> i * 10).thenApply(i -> i.toString());
System.out.println(f.get()); //"1000"

需要注意的是,这些转换并不是马上执行的,也不会阻塞,而是在前一个​​stage​​完成后继续执行。

它们与​​handle​​​方法的区别在于​​handle​​​方法会处理正常计算值和异常,因此它可以屏蔽异常,避免异常继续抛出。而​​thenApply​​方法只是用来处理正常值,因此一旦有异常就会抛出。

四. 纯消费

上面的方法是当计算完成的时候,会生成新的计算结果(​​thenApply​​​, ​​handle​​​),或者返回同样的计算结果​​whenComplete​​​,​​CompletableFuture​​​还提供了一种处理结果的方法,只对结果执行​​Action​​​,而不返回新的计算值,因此计算值为​​Void​​:

public CompletableFuture<Void>   thenAccept(Consumer<? super T> action);
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor);

看它的参数类型也就明白了,它们是函数式接口​​Consumer​​,这个接口只有输入,没有返回值。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 100;
});
CompletableFuture<Void> f = future.thenAccept(System.out::println);
System.out.println(f.get());

​thenAcceptBoth​​​以及相关方法提供了类似的功能,当两个​​CompletionStage​​​都正常完成计算的时候,就会执行提供的​​action​​​,它用来组合另外一个异步的结果。
​​​runAfterBoth​​​是当两个​​CompletionStage​​​都正常完成计算的时候,执行一个​​Runnable​​​,这个​​Runnable​​并不使用计算的结果。

public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action);
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action);
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action, Executor executor);
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action);

例子如下:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 100;
});
CompletableFuture<Void> f = future.thenAcceptBoth(CompletableFuture.completedFuture(10), (x, y) -> System.out.println(x * y));
System.out.println(f.get());

更彻底地,下面一组方法当计算完成的时候会执行一个Runnable,与​​thenAccept​​​不同,​​Runnable​​​并不使用​​CompletableFuture​​计算的结果。

public CompletableFuture<Void>   thenRun(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)

更彻底地,下面一组方法当计算完成的时候会执行一个​​Runnable​​​,与​​thenAccept​​​不同,​​Runnable​​​并不使用​​CompletableFuture​​计算的结果。

public CompletableFuture<Void>   thenRun(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)

因此先前的​​CompletableFuture​​​计算的结果被忽略了,这个方法返回​​CompletableFuture<Void>​​类型的对象。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 100;
});
CompletableFuture<Void> f = future.thenRun(() -> System.out.println("finished"));
System.out.println(f.get());

📌因此,你可以根据方法的参数的类型来加速你的记忆。​​Runnable​​​类型的参数会忽略计算的结果,​​Consumer​​​是纯消费计算结果,​​BiConsumer​​​会组合另外一个​​CompletionStage​​​纯消费,​​Function​​​会对计算结果做转换,​​BiFunction​​​会组合另外一个​​CompletionStage​​的计算结果做转换。

五. 组合

public <U> CompletableFuture<U>   thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
public <U> CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn)
public <U> CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn, Executor executor)

这一组方法接受一个​​Function​​​作为参数,这个​​Function​​​的输入是当前的​​CompletableFuture​​​的计算值,返回结果将是一个新的​​CompletableFuture​​​,这个新的​​CompletableFuture​​​会组合原来的​​CompletableFuture​​​和函数返回的​​CompletableFuture​​。因此它的功能类似:

📌A ±-> B ±–> C

记住,​​thenCompose​​​返回的对象并不一是函数​​fn​​​返回的对象,如果原来的​​CompletableFuture​​​还没有计算出来,它就会生成一个新的组合后的​​CompletableFuture​​。

例子:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 100;
});
CompletableFuture<String> f = future.thenCompose( i -> {
return CompletableFuture.supplyAsync(() -> {
return (i * 10) + "";
});
});
System.out.println(f.get()); //1000

而下面的一组方法​​thenCombine​​​用来复合另外一个​​CompletionStage​​的结果。它的功能类似:

A +
|
+------> C
+------^
B +

两个​​CompletionStage​​​是并行执行的,它们之间并没有先后依赖顺序,​​other​​​并不会等待先前的​​CompletableFuture​​执行完毕后再执行。

public <U,V> CompletableFuture<V>   thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn, Executor executor)

其实从功能上来讲,它们的功能更类似​​thenAcceptBoth​​​,只不过​​thenAcceptBoth​​​是纯消费,它的函数参数没有返回值,而​​thenCombine​​​的函数参数​​fn​​有返回值。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {return 100;});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {return "abc";});
CompletableFuture<String> f = future.thenCombine(future2, (x,y) -> y + "-" + x);
System.out.println(f.get()); //abc-100

六. Either

​thenAcceptBoth​​​和​​runAfterBoth​​​是当两个​​CompletableFuture​​​都计算完成,而我们下面要了解的方法是当任意一个​​CompletableFuture​​计算完成的时候就会执行。

public CompletableFuture<Void>   acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action)
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor)
public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T,U> fn)
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn)
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn, Executor executor)

​acceptEither​​​方法是当任意一个​​CompletionStage​​​完成的时候,​​action​​​这个消费者就会被执行。这个方法返回​​CompletableFuture<Void>​

​applyToEither​​​方法是当任意一个​​CompletionStage​​​完成的时候,​​fn​​​会被执行,它的返回值会当作新的​​CompletableFuture​​的计算结果。

下面这个例子有时会输出​​100​​​,有时候会输出​​200​​​,哪个​​Future​​先完成就会根据它的结果计算。

Random rand = new Random();
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000 + rand.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return 100;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000 + rand.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return 200;
});
CompletableFuture<String> f = future.applyToEither(future2,i -> i.toString());

七. 辅助方法 ​​allOf​​​ 和 ​​anyOf​

前面我们已经介绍了几个静态方法:​​completedFuture​​​、​​runAsync​​​、​​supplyAsync​​​,下面介绍的这两个方法用来组合多个​​CompletableFuture​​。

public static CompletableFuture<Void>       allOf(CompletableFuture<?>... cfs)
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)

​allOf​​​方法是当所有的​​CompletableFuture​​​都执行完后执行计算。
​​​anyOf​​​方法是当任意一个​​CompletableFuture​​执行完后就会执行计算,计算的结果相同。

下面的代码运行结果有时是​​100​​​,有时是​​"abc"​​​。但是​​anyOf​​​和​​applyToEither​​​不同。​​anyOf​​​接受任意多的​​CompletableFuture​​​但是​​applyToEither​​​只是判断两个​​CompletableFuture​​​,​​anyOf​​​返回值的计算结果是参数中其中一个​​CompletableFuture​​​的计算结果,​​applyToEither​​​返回值的计算结果却是要经过​​fn​​处理的。当然还有静态方法的区别,线程池的选择等。

Random rand = new Random();
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000 + rand.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return 100;
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000 + rand.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return "abc";
});
//CompletableFuture<Void> f = CompletableFuture.allOf(future1,future2);
CompletableFuture<Object> f = CompletableFuture.anyOf(future1,future2);
System.out.println(f.get());

我想通过上面的介绍,应该把​​CompletableFuture​​​的方法和功能介绍完了(​​cancel()​​​、​​isCompletedExceptionally()​​​、​​isDone()​​​以及继承于​​Object​​​的方法无需介绍了, ​​toCompletableFuture()​​​返回​​CompletableFuture​​​本身),希望你能全面了解​​CompletableFuture​​​强大的功能,并将它应用到​​Java​​的异步编程中。

如果你用过​​Guava​​​的​​Future​​​类,你就会知道它的​​Futures​​​辅助类提供了很多便利方法,用来处理多个​​Future​​​,而不像​​Java​​​的​​CompletableFuture​​​,只提供了​​allOf​​​、​​anyOf​​​两个方法。 比如有这样一个需求,将多个​​CompletableFuture​​​组合成一个​​CompletableFuture​​​,这个组合后的​​CompletableFuture​​​的计算结果是个​​List​​​,它包含前面所有的​​CompletableFuture​​​的计算结果,​​guava​​​的​​Futures.allAsList​​​可以实现这样的功能,但是对于​​java CompletableFuture​​,我们需要一些辅助方法:

public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) {
CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
return allDoneFuture.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.<T>toList()));
}
public static <T> CompletableFuture<Stream<T>> sequence(Stream<CompletableFuture<T>> futures) {
List<CompletableFuture<T>> futureList = futures.filter(f -> f != null).collect(Collectors.toList());
return sequence(futureList);
}

或者​​Java Future​​​转​​CompletableFuture​​:

public static <T> CompletableFuture<T> toCompletable(Future<T> future, Executor executor) {
return CompletableFuture.supplyAsync(() -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}, executor);
}

​github​​​有多个项目可以实现​​Java CompletableFuture​​​与其它​​Future ​​​(如​​Guava ListenableFuture​​​)之间的转换,如​​spotify/futures-extra​​​、​​future-converter​​​、​​scala/scala-java8-compat​​ 等。

八. 使用示例

​CompletionStage​​是一个接口,从命名上看得知是一个完成的阶段,它里面的方法也标明是在某个运行阶段得到了结果之后要做的事情。

8.1. 进行变换

public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn,Executor executor);

首先说明一下已​​Async​​​结尾的方法都是可以异步执行的,如果指定了线程池,会在指定的线程池中执行,如果没有指定,默认会在​​ForkJoinPool.commonPool()​​​中执行,下文中将会有好多类似的,都不详细解释了。关键的入参只有一个​​Function​​​,它是函数式接口,所以使用​​Lambda​​表示起来会更加优雅。它的入参是上一个阶段计算后的结果,返回值是经过转化后结果。

例如:

@Test
public void thenApply() {
String result = CompletableFuture.supplyAsync(() -> "hello").thenApply(s -> s + " world").join();
System.out.println(result);
}

// hello world

8.2. 进行消耗

public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);

​thenAccept​​​是针对结果进行消耗,因为他的入参是​​Consumer​​,有入参无返回值。例如:

@Test
public void thenAccept(){
CompletableFuture.supplyAsync(() -> "hello").thenAccept(s -> System.out.println(s+" world"));
}

// hello world

8.3. 对上一步的计算结果不关心,执行下一个操作

public CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);

​thenRun​​​它的入参是一个​​Runnable​​的实例,表示当得到上一步的结果时的操作。 例如:

@Test
public void thenRun(){
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}).thenRun(() -> System.out.println("hello world"));
while (true){}
}
// hello world

8.4. 结合两个CompletionStage的结果,进行转化后返回

public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor);

它需要原来的处理返回值,并且​​other​​​代表的​​CompletionStage​​也要返回值之后,利用这两个返回值,进行转换后返回指定类型的值。 例如:

@Test
public void thenCombine() {
String result = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}).thenCombine(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "world";
}), (s1, s2) -> s1 + " " + s2).join();
System.out.println(result);
}
// hello world

8.5. 结合两个CompletionStage的结果,进行消耗

public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action, Executor executor);

它需要原来的处理返回值,并且other代表的​​CompletionStage​​也要返回值之后,利用这两个返回值,进行消耗。 例如:

@Test
public void thenAcceptBoth() {
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}).thenAcceptBoth(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "world";
}), (s1, s2) -> System.out.println(s1 + " " + s2));
while (true){}
}
// hello world

8.6. 在两个CompletionStage都运行完执行

public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor);

不关心这两个​​CompletionStage​​​的结果,只关心这两个​​CompletionStage​​​执行完毕,之后在进行操作(​​Runnable​​)。 例如:

@Test
public void runAfterBoth(){
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "s1";
}).runAfterBothAsync(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "s2";
}), () -> System.out.println("hello world"));
while (true){}
}
// hello world

8.7. 两个CompletionStage,谁计算的快,我就用那个CompletionStage的结果进行下一步的转化操作。

public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn,Executor executor);

我们现实开发场景中,总会碰到有两种渠道完成同一个事情,所以就可以调用这个方法,找一个最快的结果进行处理。

@Test
public void applyToEither() {
String result = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "s1";
}).applyToEither(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello world";
}), s -> s).join();
System.out.println(result);
}
// hello world

8.8. 两个CompletionStage,谁计算的快,我就用那个CompletionStage的结果进行下一步的消耗操作。

public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action,Executor executor);

例子:

@Test
public void acceptEither() {
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "s1";
}).acceptEither(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello world";
}), System.out::println);
while (true){}
}
// hello world

8.9. 两个CompletionStage,任何一个完成了都会执行下一步的操作(Runnable)

public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor);

例子:

@Test
public void runAfterEither() {
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "s1";
}).runAfterEither(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "s2";
}), () -> System.out.println("hello world"));
while (true) {
}
}
// hello world

8.10. 当运行时出现了异常,可以通过exceptionally进行补偿

public CompletionStage<T> exceptionally(Function<Throwable, ? extends T> fn);

例子:

@Test
public void exceptionally() {
String result = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (1 == 1) {
throw new RuntimeException("测试一下异常情况");
}
return "s1";
}).exceptionally(e -> {
System.out.println(e.getMessage());
return "hello world";
}).join();
System.out.println(result);
}
// java.lang.RuntimeException: 测试一下异常情况
// hello world

8.11. 当运行完成时,对结果的记录

这里的完成时有两种情况,一种是正常执行,返回值。另外一种是遇到异常抛出造成程序的中断。这里为什么要说成记录,因为这几个方法都会返回​​CompletableFuture​​​,当​​Action​​​执行完毕后它的结果返回原始的​​CompletableFuture​​的计算结果或者返回异常。所以不会对结果产生任何的作用。

public CompletionStage<T> whenComplete(BiConsumer<? super T, ? super Throwable> action);
public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action);
public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action,Executor executor);

例子:

@Test
public void whenComplete() {
String result = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (1 == 1) {
throw new RuntimeException("测试一下异常情况");
}
return "s1";
}).whenComplete((s, t) -> {
System.out.println(s);
System.out.println(t.getMessage());
}).exceptionally(e -> {
System.out.println(e.getMessage());
return "hello world";
}).join();
System.out.println(result);
}
// null
// java.lang.RuntimeException: 测试一下异常情况
// java.lang.RuntimeException: 测试一下异常情况
// hello world

这里也可以看出,如果使用了​​exceptionally​​​,就会对最终的结果产生影响,它没有口子返回如果没有异常时的正确的值,这也就引出下面我们要介绍的​​handle​​。

8.12. 运行完成时,对结果的处理

这里的完成时有两种情况,一种是正常执行,返回值。另外一种是遇到异常抛出造成程序的中断。

public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);

例如: 出现异常时

@Test
public void handle() {
String result = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//出现异常
if (1 == 1) {
throw new RuntimeException("测试一下异常情况");
}
return "s1";
}).handle((s, t) -> {
if (t != null) {
return "hello world";
}
return s;
}).join();
System.out.println(result);
}
// hello world

未出现异常时

@Test
public void handle() {
String result = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "s1";
}).handle((s, t) -> {
if (t != null) {
return "hello world";
}
return s;
}).join();
System.out.println(result);
}
// s1

上面就是​​CompletionStage​​​接口中方法的使用实例,​​CompletableFuture​​​同样也同样实现了​​Future​​​,所以也同样可以使用​​get​​​进行阻塞获取值,总的来说,​​CompletableFuture​​使用起来还是比较爽的,看起来也比较优雅一点。