并发编程-CompleteableFuture

CompleteableFuture

JDK1.8才新加入的一个实现类CompletableFuture,实现了Future, CompletionStage两个接口。实现了Future接口,意味着可以通过阻塞或者轮询的方式获得结果。CompletionStage是一个接口,从命名上看得知是一个完成的阶段,它代表了一个特定的计算的阶段,可以同步或者异步的被完成。

创建

除了直接new出一个CompletableFuture的实例,还可以通过工厂方法创建CompletableFuture的实例:

/**
 * Returns a new CompletableFuture that is asynchronously completed
 * by a task running in the {@link ForkJoinPool#commonPool()} with
 * the value obtained by calling the given Supplier.
 *
 * @param supplier a function returning the value to be used
 * to complete the returned CompletableFuture
 * @param <U> the function's return type
 * @return the new CompletableFuture
 */
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
	return asyncSupplyStage(asyncPool, supplier);
}

/**
 * Returns a new CompletableFuture that is asynchronously completed
 * by a task running in the given executor with the value obtained
 * by calling the given Supplier.
 *
 * @param supplier a function returning the value to be used
 * to complete the returned CompletableFuture
 * @param executor the executor to use for asynchronous execution
 * @param <U> the function's return type
 * @return the new CompletableFuture
 */
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
												   Executor executor) {
	return asyncSupplyStage(screenExecutor(executor), supplier);
}

/**
 * Returns a new CompletableFuture that is asynchronously completed
 * by a task running in the {@link ForkJoinPool#commonPool()} after
 * it runs the given action.
 *
 * @param runnable the action to run before completing the
 * returned CompletableFuture
 * @return the new CompletableFuture
 */
public static CompletableFuture<Void> runAsync(Runnable runnable) {
	return asyncRunStage(asyncPool, runnable);
}

/**
 * Returns a new CompletableFuture that is asynchronously completed
 * by a task running in the given executor after it runs the given
 * action.
 *
 * @param runnable the action to run before completing the
 * returned CompletableFuture
 * @param executor the executor to use for asynchronous execution
 * @return the new CompletableFuture
 */
public static CompletableFuture<Void> runAsync(Runnable runnable,
											   Executor executor) {
	return asyncRunStage(screenExecutor(executor), runnable);
}

Asynsc表示异步;runAsync异步返回一个结果,supplyAsync返回void;第二个参数Executor表示自己创建的线程池,否则采用默认的ForkJoinPool.commonPool()线程池

获得结果的方法:
/**
 * Waits if necessary for this future to complete, and then
 * returns its result.
 *
 * @return the result value
 * @throws CancellationException if this future was cancelled
 * @throws ExecutionException if this future completed exceptionally
 * @throws InterruptedException if the current thread was interrupted
 * while waiting
 */
public T get() throws InterruptedException, ExecutionException {
	Object r;
	return reportGet((r = result) == null ? waitingGet(true) : r);
}

/**
 * Waits if necessary for at most the given time for this future
 * to complete, and then returns its result, if available.
 *
 * @param timeout the maximum time to wait
 * @param unit the time unit of the timeout argument
 * @return the result value
 * @throws CancellationException if this future was cancelled
 * @throws ExecutionException if this future completed exceptionally
 * @throws InterruptedException if the current thread was interrupted
 * while waiting
 * @throws TimeoutException if the wait timed out
 */
public T get(long timeout, TimeUnit unit)
	throws InterruptedException, ExecutionException, TimeoutException {
	Object r;
	long nanos = unit.toNanos(timeout);
	return reportGet((r = result) == null ? timedGet(nanos) : r);
}

/**
 * join返回计算的结果或者抛出一个unchecked异常(CompletionException),它和get对抛出的异常的处理有些细微的区别。
 * Returns the result value when complete, or throws an
 * (unchecked) exception if completed exceptionally. To better
 * conform with the use of common functional forms, if a
 * computation involved in the completion of this
 * CompletableFuture threw an exception, this method throws an
 * (unchecked) {@link CompletionException} with the underlying
 * exception as its cause.
 *
 * @return the result value
 * @throws CancellationException if the computation was cancelled
 * @throws CompletionException if this future completed
 * exceptionally or a completion computation threw an exception
 */
public T join() {
	Object r;
	return reportJoin((r = result) == null ? waitingGet(false) : r);
}

/**
 * 如果结果已经计算完则返回结果或者抛出异常,否则返回给定的valueIfAbsent值。
 * Returns the result value (or throws any encountered exception)
 * if completed, else returns the given valueIfAbsent.
 *
 * @param valueIfAbsent the value to return if not completed
 * @return the result value, if completed, else the given valueIfAbsent
 * @throws CancellationException if the computation was cancelled
 * @throws CompletionException if this future completed
 * exceptionally or a completion computation threw an exception
 */
public T getNow(T valueIfAbsent) {
	Object r;
	return ((r = result) == null) ? valueIfAbsent : reportJoin(r);
}

辅助方法

allOf方法是当所有的CompletableFuture都执行完后执行计算。

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

/**
 * Returns a new CompletableFuture that is completed when all of
 * the given CompletableFutures complete.  If any of the given
 * CompletableFutures complete exceptionally, then the returned
 * CompletableFuture also does so, with a CompletionException
 * holding this exception as its cause.  Otherwise, the results,
 * if any, of the given CompletableFutures are not reflected in
 * the returned CompletableFuture, but may be obtained by
 * inspecting them individually. If no CompletableFutures are
 * provided, returns a CompletableFuture completed with the value
 * {@code null}.
 *
 * <p>Among the applications of this method is to await completion
 * of a set of independent CompletableFutures before continuing a
 * program, as in: {@code CompletableFuture.allOf(c1, c2,
 * c3).join();}.
 *
 * @param cfs the CompletableFutures
 * @return a new CompletableFuture that is completed when all of the
 * given CompletableFutures complete
 * @throws NullPointerException if the array or any of its elements are
 * {@code null}
 */
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
	return andTree(cfs, 0, cfs.length - 1);
}

/**
 * Returns a new CompletableFuture that is completed when any of
 * the given CompletableFutures complete, with the same result.
 * Otherwise, if it completed exceptionally, the returned
 * CompletableFuture also does so, with a CompletionException
 * holding this exception as its cause.  If no CompletableFutures
 * are provided, returns an incomplete CompletableFuture.
 *
 * @param cfs the CompletableFutures
 * @return a new CompletableFuture that is completed with the
 * result or exception of any of the given CompletableFutures when
 * one completes
 * @throws NullPointerException if the array or any of its elements are
 * {@code null}
 */
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
	return orTree(cfs, 0, cfs.length - 1);
}

CompletableFuture方法归类

变换类 thenApply:
public <U> CompletableFuture<U> thenApply(
	Function<? super T,? extends U> fn) {
	return uniApplyStage(null, fn);
}

public <U> CompletableFuture<U> thenApplyAsync(
	Function<? super T,? extends U> fn) {
	return uniApplyStage(asyncPool, fn);
}

public <U> CompletableFuture<U> thenApplyAsync(
	Function<? super T,? extends U> fn, Executor executor) {
	return uniApplyStage(screenExecutor(executor), fn);
}

关键入参是函数式接口Function。它的入参是上一个阶段计算后的结果,返回值是经过转化后结果。

消费类 thenAccept:
public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
	return uniAcceptStage(null, action);
}

public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
	return uniAcceptStage(asyncPool, action);
}

public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
											   Executor executor) {
	return uniAcceptStage(screenExecutor(executor), action);
}

关键入参是函数式接口Consumer。它的入参是上一个阶段计算后的结果, 没有返回值。

执行操作类 thenRun:
public CompletableFuture<Void> thenRun(Runnable action) {
	return uniRunStage(null, action);
}

public CompletableFuture<Void> thenRunAsync(Runnable action) {
	return uniRunStage(asyncPool, action);
}

public CompletableFuture<Void> thenRunAsync(Runnable action,
											Executor executor) {
	return uniRunStage(screenExecutor(executor), action);
}

对上一步的计算结果不关心,执行下一个操作,入参是一个Runnable的实例,表示上一步完成后执行的操作。

结合转化类:
public <U,V> CompletableFuture<V> thenCombine(
	CompletionStage<? extends U> other,
	BiFunction<? super T,? super U,? extends V> fn) {
	return biApplyStage(null, other, fn);
}

public <U,V> CompletableFuture<V> thenCombineAsync(
	CompletionStage<? extends U> other,
	BiFunction<? super T,? super U,? extends V> fn) {
	return biApplyStage(asyncPool, other, fn);
}

public <U,V> CompletableFuture<V> thenCombineAsync(
	CompletionStage<? extends U> other,
	BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
	return biApplyStage(screenExecutor(executor), other, fn);
}

需要上一步的处理返回值,并且other代表的CompletionStage 有返回值之后,利用这两个返回值,进行转换后返回指定类型的值。

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

结合转化类:
public <U> CompletableFuture<U> thenCompose(
	Function<? super T, ? extends CompletionStage<U>> fn) {
	return uniComposeStage(null, fn);
}

public <U> CompletableFuture<U> thenComposeAsync(
	Function<? super T, ? extends CompletionStage<U>> fn) {
	return uniComposeStage(asyncPool, fn);
}

public <U> CompletableFuture<U> thenComposeAsync(
	Function<? super T, ? extends CompletionStage<U>> fn,
	Executor executor) {
	return uniComposeStage(screenExecutor(executor), fn);
}

对于Compose可以连接两个CompletableFuture,其内部处理逻辑是当第一个CompletableFuture处理没有完成时会合并成一个CompletableFuture,如果处理完成,第二个future会紧接上一个CompletableFuture进行处理。

第一个CompletableFuture 的处理结果是第二个future需要的输入参数。

结合消费类:
public <U> CompletableFuture<Void> thenAcceptBoth(
	CompletionStage<? extends U> other,
	BiConsumer<? super T, ? super U> action) {
	return biAcceptStage(null, other, action);
}

public <U> CompletableFuture<Void> thenAcceptBothAsync(
	CompletionStage<? extends U> other,
	BiConsumer<? super T, ? super U> action) {
	return biAcceptStage(asyncPool, other, action);
}

public <U> CompletableFuture<Void> thenAcceptBothAsync(
	CompletionStage<? extends U> other,
	BiConsumer<? super T, ? super U> action, Executor executor) {
	return biAcceptStage(screenExecutor(executor), other, action);
}

需要上一步的处理返回值,并且other代表的CompletionStage 有返回值之后,利用这两个返回值,进行消费

运行后执行类:
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
											Runnable action) {
	return biRunStage(null, other, action);
}

public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
												 Runnable action) {
	return biRunStage(asyncPool, other, action);
}

public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
												 Runnable action,
												 Executor executor) {
	return biRunStage(screenExecutor(executor), other, action);
}

不关心这两个CompletionStage的结果,只关心这两个CompletionStage都执行完毕,之后再进行操作(Runnable)。

取最快转换类:
public <U> CompletableFuture<U> applyToEither(
	CompletionStage<? extends T> other, Function<? super T, U> fn) {
	return orApplyStage(null, other, fn);
}

public <U> CompletableFuture<U> applyToEitherAsync(
	CompletionStage<? extends T> other, Function<? super T, U> fn) {
	return orApplyStage(asyncPool, other, fn);
}

public <U> CompletableFuture<U> applyToEitherAsync(
	CompletionStage<? extends T> other, Function<? super T, U> fn,
	Executor executor) {
	return orApplyStage(screenExecutor(executor), other, fn);
}

两个CompletionStage,谁计算的快,我就用那个CompletionStage的结果进行下一步的转化操作。现实开发场景中,总会碰到有两种渠道完成同一个事情,所以就可以调用这个方法,找一个最快的结果进行处理。

取最快消费类:
public CompletableFuture<Void> acceptEither(
	CompletionStage<? extends T> other, Consumer<? super T> action) {
	return orAcceptStage(null, other, action);
}

public CompletableFuture<Void> acceptEitherAsync(
	CompletionStage<? extends T> other, Consumer<? super T> action) {
	return orAcceptStage(asyncPool, other, action);
}

public CompletableFuture<Void> acceptEitherAsync(
	CompletionStage<? extends T> other, Consumer<? super T> action,
	Executor executor) {
	return orAcceptStage(screenExecutor(executor), other, action);
}

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

取最快运行后执行类:
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
											  Runnable action) {
	return orRunStage(null, other, action);
}

public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
												   Runnable action) {
	return orRunStage(asyncPool, other, action);
}

public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
												   Runnable action,
												   Executor executor) {
	return orRunStage(screenExecutor(executor), other, action);
}

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

异常补偿类:
public CompletableFuture<T> exceptionally(
	Function<Throwable, ? extends T> fn) {
	return uniExceptionallyStage(fn);
}

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

运行后记录结果类:
public CompletableFuture<T> whenComplete(
	BiConsumer<? super T, ? super Throwable> action) {
	return uniWhenCompleteStage(null, action);
}

public CompletableFuture<T> whenCompleteAsync(
	BiConsumer<? super T, ? super Throwable> action) {
	return uniWhenCompleteStage(asyncPool, action);
}

public CompletableFuture<T> whenCompleteAsync(
	BiConsumer<? super T, ? super Throwable> action, Executor executor) {
	return uniWhenCompleteStage(screenExecutor(executor), action);
}

action执行完毕后它的结果返回原始的CompletableFuture的计算结果或者返回异常。所以不会对结果产生任何的作用。

运行后处理结果类:
public <U> CompletableFuture<U> handle(
	BiFunction<? super T, Throwable, ? extends U> fn) {
	return uniHandleStage(null, fn);
}

public <U> CompletableFuture<U> handleAsync(
	BiFunction<? super T, Throwable, ? extends U> fn) {
	return uniHandleStage(asyncPool, fn);
}

public <U> CompletableFuture<U> handleAsync(
	BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
	return uniHandleStage(screenExecutor(executor), fn);
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值