沉默可能产生误解,我需要说话,说话将我推向歧途,我必须沉默。赫塔·米勒——《国王鞠躬,国王杀人》

好问题,尝试一下

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;

class Scratch {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
CompletableFuture.runAsync(() -> Stream.generate(Object::new).forEach(System.out::println)).get(2, TimeUnit.SECONDS);
Thread.currentThread().join();
}
}

发现两秒后断开了

image-20221119212106573

那我们try下异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;

class Scratch {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
try {
CompletableFuture.runAsync(() -> Stream.generate(Object::new).forEach(System.out::println)).get(2, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.err.println("Timeout");
}
Thread.currentThread().join();
}
}

并没有断开,仍然在执行

image-20221119212209130

因此,CompletableFuture的异步任务如果超时异常try掉了,是不会停止执行的