CompletableFuture get 与 join区别

4,760 阅读1分钟

相同点

  1. 二者都会当任务完成时,返回 Future 结果。
  • get():Waits if necessary for this future to complete, and then returns its result.
  • join():Returns the result value when complete
  1. 如果计算被取消抛出异常:CancellationException
@throws CancellationException if the computation was cancelled

不同点

  1. 异常处理不同:
  • get():抛出的是经过检查的异常,ExecutionException, InterruptedException 需要用户手动处理(抛出或者 try catch)
  • join():抛出的是uncheck异常(即继承RuntimeException),不会强制开发者抛出,会将异常包装成CompletionException异常,异常原因为代码中存在的真正的异常。
  1. get 方法可设置任务阻塞超时时间,具体方法:
/**
 * 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);
}