向 java.util.concurrent.Future.get(long, TimeUnit)
提供负超时是否安全? ?文档说
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.
这是否意味着它将适用于负值,或者该声明仅涵盖非负值情况?我期望的行为是如果结果可用则返回结果,否则立即超时。如果我们要计算某个绝对时间点的超时,而该时间点已经过去,则可能会出现这种情况。我当然可以使用max{timeout, 0}
,但这真的有必要吗?在我的环境中进行的测试表明它有效,但这能保证吗? https://stackoverflow.com/questions/9332904/behavior-of-future-get-with-0-timeout指出这应该是 0 超时的情况。
或者换句话说:
假设 Future
的结果可用。会实现 Future
不合规,如果 get(long, TimeUnit)
使用负超时调用除了返回此结果之外还会做其他事情吗?
最佳答案
“最多”等待一段时间是不可能的;唯一的理论保证是等待时间将不少于某个数字。这实际上是在 JLS 中指定的。因此,该措辞必须解读如下:
Let t be the given time to wait, and let u be the time this method actually spent before returning control to the caller. If and only if u < t, the return value of the method call is guaranteed to be the return value of the Future.
鉴于上述情况,负数 t 完全符合顺序,并且所有 <= 0 的值应该表现完全相同。
不过,可以想象,实现可能会因等待时间为负而抛出异常,并且这样做的借口很弱。如果您的代码由于此类异常而失败,您可能会与所述 Future
实现的作者展开激烈争论。如果发生这种情况,Stack Overflow 上确实没有任何答案可以阻止它。
如果您随后上法庭解决损害责任,并且对此类诉讼的结果感兴趣,那么我相信这种担忧超出了 Stack Overflow 的范围。
关于java - Future.get(long, TimeUnit) 的负超时安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21779535/