一.相同點:
join()和get()方法都是用來獲取CompletableFuture異步之后的返回值
二.區別:
1.join()方法拋出的是uncheck異常(即未經檢查的異常),不會強制開發者拋出,
會將異常包裝成CompletionException異常 /CancellationException異常,但是本質原因還是代碼內存在的真正的異常,
文檔說明:
/** * 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 */
demo:
public static void main(String[] args) { CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> { int i =1/0; return 1; }); CompletableFuture.allOf(f1).join(); System.out.println("CompletableFuture Test"); }
異常信息
Exception in thread "main" java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:273) at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:280) at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1592) at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1582) at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056) at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) Caused by: java.lang.ArithmeticException: / by zero at com.gabriel.stage.utils.IpAddressUtil.lambda$main$0(IpAddressUtil.java:44) at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) ... 5 more
2.get()方法拋出的是經過檢查的異常,ExecutionException, InterruptedException 需要用戶手動處理(拋出或者 try catch)
文檔說明
/** * 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 */
demo
public static void main(String[] args) throws ExecutionException, InterruptedException { CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> { int i =1/0; return 1; }); f1.get(); System.out.println("CompletableFuture Test"); }