CompletableFuture详解~join与get的区别

一.相同点:

join()和get()方法都是用来获取CompletableFuture异步之后的返回值

二.区别:

1.join()方法抛出的是uncheck异常(即RuntimeException),不会强制开发者抛出,

  会将异常包装成CompletionException异常 /CancellationException异常,但是本质原因还是代码内存在的真正的异常,

    public static void main(String[] args) {
        CompletableFuture 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)

public static void main(String[] args) {
        CompletableFuture f1 = CompletableFuture.supplyAsync(() -> {
            int i =1/0;
            return 1;
        });
        
		try {
			f1.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println("CompletableFuture Test");
    }

你可能感兴趣的:(Java并发,Java,java,开发语言,后端)