[英]Behavior of future.get with 0 timeout
Can anyone point me to some documentation that makes clear that a 'Future.get` with a timeout of 0 will not wait? 任何人都可以向我指出一些文档,明确表示超时为0的'Future.get`不会等待吗?
The API docs for java.util.concurrent.Future
does not make explicit the behavior of future.get(0, unit)
. java.util.concurrent.Future
的API文档没有明确future.get(0, unit)
的行为。 Standing on its own, the statement "Waits if necessary for at most the given time..." implies this invocation will not wait at all, but given the long-standing behavior of Object.wait(0)
(infinite wait), I'm nervous to depend on a "no wait" behavior of future.get(0, unit)
站在它自己的声明“如果有必要等待最多给定时间......”意味着这个调用将不会等待,但考虑到
Object.wait(0)
(无限等待)的长期行为,我我很紧张,依赖于future.get(0, unit)
的“无等待”行为。 future.get(0, unit)
Scanning the source of some JDK-provided classes (viz. FutureTask
) I see that this particular implementation of Future
does not wait when the timeout is 0. 扫描一些JDK提供的类(即
FutureTask
)的源代码我发现当超时为0时, Future
这个特定实现不会等待。
I'd like to be able to say 我想能说
long timeout = Math.max(until - now, 0);
return future.get(timeout, TimeUnit.MILLISECONDS);
but I'm nervous about a Future implementing that as an infinite wait, so instead, I've explicitly coded it the way I would expect it to work: 但我很担心未来实现这是一个无限的等待,所以相反,我已经按照我希望它的工作方式明确编码:
long timeout = Math.max(until - now, 0);
if(timeout > 0 || future.isDone()){
return future.get(timeout, TimeUnit.MILLISECONDS);
} else {
throw TimeoutException();
}
Waits if necessary for at most the given time…
如果有必要等待最多给定时间......
Waiting for at most zero time units is not waiting at all. 等待最多零时间单位并不等待。 That's not an implicit hint, it's an explicit guarantee.
这不是一个隐含的暗示,它是一个明确的保证。
Can anyone point me to some documentation that makes clear that a 'Future.get` with a timeout of 0 will not wait?
任何人都可以向我指出一些文档,明确表示超时为0的'Future.get`不会等待吗?
I can point you at some code if that helps. 如果有帮助,我可以指出一些代码。 Looking into
java.util.concurrent.FutureTask
and then on to AbstractQueuedSynchronizer
I see the following loop which I've pared down to show the relavent bits: 查看
java.util.concurrent.FutureTask
,然后查看AbstractQueuedSynchronizer
我看到以下循环,我已经减少了显示相关位:
private boolean doAcquireSharedNanos(int arg, long nanosTimeout) {
long lastTime = System.nanoTime();
for (;;) {
...
if (nanosTimeout <= 0) {
cancelAcquire(node);
return false;
}
long now = System.nanoTime();
nanosTimeout -= now - lastTime;
}
This means that if nanosTimeout
is 0 (which it will be if you pass in 0 to get) then it will try to acquire the future once and then timeout and return false. 这意味着如果
nanosTimeout
为0(如果你传入0来获取它将是它),那么它将尝试获取未来一次然后超时并返回false。
If it makes you feel any better, you can set your timeout to be 1 nanosecond. 如果它让您感觉更好,您可以将超时设置为1纳秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.