Java Reference
In-Depth Information
As depicted in figure 11.3 , this style of programming allows your thread to perform some other
tasks while the long-lasting operation is executed concurrently in a separate thread provided by
the ExecutorService. Then, when you can't do any other meaningful work without having the
result of that asynchronous operation, you can retrieve it from the Future by invoking its get
method. This method immediately returns the result of the operation if it's already completed or
blocks your thread, waiting for its result to be available.
Figure 11.3. Using a Future to execute a long operation asynchronously
Can you think of a problem with this scenario? What if the long operation never returns? To
handle this possibility, even though there also exists a get method that doesn't take a parameter,
it's almost always a good idea to use its overloaded version, accepting a timeout defining the
maximum time your thread has to wait for the Future's result, as you did in listing 11.1 , instead
of waiting indefinitely.
11.1.1. Futures limitations
This first small example shows that the Future interface provides methods to check if the
asynchronous computation is complete (using the isDone method), to wait for its completion,
and to retrieve its result. But these features aren't enough to let you write concise concurrent
code. For example, it's difficult to express dependencies between results of a Future;
declaratively it's easy to say, “When the result of the long computation is available, please send
its result to another long computation, and when that's done, combine its result with the result
 
Search WWH ::




Custom Search