A future task is essentially an asynchronous construct. As its name signifies, it is a wrapper for some expensive computation whose result will be available sometime in the future. Once the computation is completed, it returns the result via a
get() method call.
As listed and shown in the figure, the future task have three states:
- Waiting to run
When we try to obtain a result from the future task, the behavior depends on which state it is in. If it is not completed yet, the thread calling
get() sleeps till the computation is done, and the result is available. There is also an overloaded
get(long timeout, TimeUnit unit) method that avoids waiting forever. So, task
get(5L, TimeUnit.SECONDS) would wait for only five seconds. If the method does not return within the time prescribed, a
TimeOutException will be thrown.
The following code shows the future task in action:
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import...