gpt4 book ai didi

java - `TimeoutException` 和 `CancellationException` 之间的区别

转载 作者:行者123 更新时间:2023-12-01 18:00:39 25 4
gpt4 key购买 nike

根据 Javadoc,Future.get() ,抛出 TimeoutExceptionCancellationException 以及另外 2 个异常。

TimeoutExceptionCancellationException 之间有什么区别?

据我所知,当线程超时并因此执行器取消它时,会抛出CancellationException。那么什么时候会抛出 TimeoutException 呢?是否存在超时线程未取消的情况?

CancellationException when using ExecutorServiceWhat is the best way to handle an ExecutionException?以及其他。

TIA。

//----------------

更新

除非开发人员明确调用,否则没有人会调用 Future.cancel() 吗?

javadoc没有提及任何关于它引起的 CancellationException 的内容。

我的系统中有一个代码,由于某些时间限制,我可能必须取消该代码。但是,我必须能够判断 Future.cancel() 何时返回 true,它这样做是因为任务已完成或已取消。从表面上看,Future.cancel() 在这两种情况下都返回 true。 Future.isDone()或其任何其他方法都没有帮助。

最佳答案

From what i know, CancellationException is thrown when the thread timed-out and thus the executor cancelled it.

没有。如果在任务完成之前调用 Futurecancel() 方法及其任一 get() 方法,则会引发 CancellationException 方法随后被调用。

But then when is TimeoutException thrown?

如果指定的时间过去了但没有执行任务,则 Future.get(long, Timeunit) 会抛出

TimeoutException(不是 CancellationException)完成。

is there a case that the timed-thread timed-out and not cancelled?

是的。超时与取消完全不同。

<小时/>

关于更新:

does nayone else call Future.cancel() unless the developer explicitly does?

只有引用特定 Future 的人才能调用其 cancel() 方法。 ExecutorService 不会调用它,如果这就是您的意思,特别是超时与取消不同,因此不会导致 CancellationExceptions。

javadoc isn't mentioning anything about CancellationException caused by it.

Future.cancel() 的 Javadoc 没有提及它,我也没有看到它这样做的特殊需要。 The exception's own class-level javadocs解释其重要性,以及可以将其抛出的那些 Future 方法的 javadoc 文档。

i've got a code coming into the system and i may have to cancel that code due to certain time-limit.

所以听起来您会调用 Future.get() 的两个参数版本来指定时间限制,然后在超时的情况下(由 >TimeoutException),您将调用 Future.cancel()

but then, i gotta be able to tell when Future.cancel() returns true, it did so because the task is completed or it is cancelled. From what it seems, Future.cancel() is returning true in both of these cases.

你从哪里得到的?您自己引用的 Future.cancel() 文档说该方法返回

false if the task could not be cancelled, typically because it has already completed normally; true otherwise

因此,如果 Future.cancel() 返回 true 那么您可以确信最终结果由 Future 表示的任务已成功取消,即不会产生任何结果,并且后续调用其 get() 方法之一将抛出 CancellationException。如果它还没有开始,那么它永远不会开始;如果它已经开始,那么它就被中断了。

后一种选择需要将 true 传递给 Future.cancel(),在这种情况下,任务实际停止取决于其实现对其线程的响应打断了。目前尚不清楚,如果任务实际上并未停止运行,则取消正在进行的任务是否被视为成功;这实际上可能取决于实现。

关于java - `TimeoutException` 和 `CancellationException` 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41232339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com