10.8 Executing Tasks Without an ExecutorService
So what happens when you just have one little Callable object that you
want to execute, and you don't need the overhead of ExectorService?
Well, it seems those Sun guys thought of everything (except perhaps
open sourcing Java)you use FutureTask.
10.8.1 How do I do that?
java.util.concurrent.FutureTask can be wrapped around Callable
objects, allowing them to behave like a Future implementation returned
from ExecutorService.submit( ). The syntax is similar as well:
The methods available to FutureTask are similar to Future, so I'll leave it to you to check out the Javadoc. With the details from Using Callable Objects, you shouldn't have any problems.
FutureTask<BigInteger> task =
new FutureTask<BigInteger>(new RandomPrimeSearch(512));
new Thread(task).start( );
BigInteger result = task.get( );
10.8.2 What about...
...good old Runnable? Fortunately, plain old Thread and Runnable didn't
get left out of the mix. You can wrap a FutureTask around a Runnable
object just as easily as you can around a Callable object, and the same
functionality applies. However, since Runnable's run( ) method doesn't return a result, the constructor is a bit different:
You have to supply a value to the constructor, of the type specified by
FutureTask<String> task =
new FutureTask<String>(new MyRunnableObject, "Success!");
your parameterization (in this example, a String), which is returned by
get( ) if execution is successful. While the above example is valid, there
are really only two common variants when using Runnable FutureTasks:
The first allows for discarding the result of get( ) altogether, and the second provides a true/false check for the result of get( ). You'd do well to use one of these yourself.
FutureTask<Object> task = new FutureTask<Object>(runnable, null);
FutureTask<Boolean> task = new FutureTask<Boolean>(runnable, true);