【发布时间】:2020-02-29 05:01:47
【问题描述】:
在解决任务时,我注意到一个我无法解释的行为。
我的任务是读取 InputStream 并在超时后中断该读取。尽管很多人说阻塞读取不能被中断,但我使用CompletableFuture实现了这个目标
public void startReader() {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> doRead(System.in));
future.get(5, TimeUnit.SECONDS);
}
private void doRead(InputStream in) {
try {
new BufferedReader(new InputStreamReader(in)).readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
但是当我使用Future 实现相同的功能时,我可以看到TimeoutException 被扔进了JVM,但我仍然可以看到读取线程没有终止并且仍在运行。
public void startReader() throws ExecutionException, InterruptedException, TimeoutException {
Future<?> future = Executors.newSingleThreadExecutor().submit(() -> doRead(System.in));
future.get(5, TimeUnit.SECONDS);
}
private void doRead(InputStream in) {
try {
new BufferedReader(new InputStreamReader(in)).readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
为什么会有这样的差异?我相信CompletableFuture 不会变魔术
【问题讨论】:
标签: java future completable-future