Problem:

How to use Java Callable to run tasks that actually return results? In this post we’ll show how to use ExecutorService to run tasks in separate threads to compute and return results.

Solution:

In the following example we’re going to use another feature from fantastic java.util.concurrent package: Callable<T>. The interface is a sister of Runnable, which you could see in action in our previous posts (Java Runnable, Java ExecutorService, and others). There are a couple of differences between them:

Callable<T> returns a Future<T> that will return a result… in the future. :-)

Callable<T> is parametrized with result’s type.

Callable’s method is called call() and may throw an Exception.

To perform our computation we’re going to use ExecutorService‘s. The method for Callables is <T> Future<T> submit(Callable<T>), which just submits given task to the executor for execution in a thread, and returns an object (Future<T>), which will have a result of computation when it’s finished.

As you can see the code is straightforward. We’re creating task, submit them to the executor and collect futures. Later we’re going through futures to get results. To do that we’re using get() method, which blocks and waits for the result. If you don’t want to wait indefinitely long, you can use get(long timeout, TimeUnit unit) that allows to wait only for specified time. There’s also another useful method – isDone(). It allows to check without blocking whether a future already has a result.