Java - Future.get() multiple invocations

岁酱吖の 提交于 2021-02-06 09:43:32

问题


How does Java's Future.get() behave in the case where it is called multiple times after the task is completed? Does it return the the same result? Or does throw an ExecutionException again and again with the same exception if the computation failed? I can not find anything in the docs about it!


回答1:


You can call get() on a Future as often as you like, and it will only block if the task that produces the result has not finished yet.

If the task has already finished, it will just immediately return the result of the task.

If the task has failed with an exception, calling get() will throw an ExecutionException each time you call it.




回答2:


I can not find anything in the docs about it!

Have you read them ? because when I read them I got the Answer and here it is ....

V get()
throws InterruptedException,
      ExecutionException

Waits if necessary for the computation to complete, and then retrieves its result.

Returns:
    the computed result

Throws:
    CancellationException - if the computation was cancelled
    ExecutionException - if the computation threw an exception
    InterruptedException - if the current thread was interrupted while waiting

If Computation is not completed it will wait , and if it has already completed it will return result ASAP , no matter how many times you call it



来源:https://stackoverflow.com/questions/28648880/java-future-get-multiple-invocations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!