Tech and Media Labs
This site uses cookies to improve the user experience.


Java Callable

Jakob Jenkov
Last update: 2018-10-27

The Java Callable interface, java.util.concurrent.Callable, represents an asynchronous task which can be executed by a separate thread. For instance, it is possible to submit a Callable object to a Java ExecutorService which will then execute it asynchronously.

Java Callable Interface Definition

The Java Callable interface is quite simple. It contains a single method named call(). Here is how the Callable interface looks (approximately):

public interface Callable<V> {

    V call() throws Exception;

}

The call() method is called in order to execute the asynchronous task. The call() method can return a result. If the task is executed asynchronously, the result is typically propagated back to the creator of the task via a Java Future. This is the case when a Callable is submitted to an ExecutorService for concurrent execution.

The call() method can also thrown an Exception in case the task fails during execution.

Implementing Callable

Here is a simple example of implementing the Java Callable interface:

public class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        return String.valueOf(System.currentTimeMillis());
    }
}

This implementation is very simple. It has the generic type set to a Java String. The result of that is that the call() method will return a String. The call() implementation just returns a String representation of the current time in milliseconds. In a real application the task would probably be a more complex, or larger, set of operations.

Quite often, IO operations like reading from or writing to disk or network, are good candidates for tasks that can be executed concurrently. IO operations often have long waiting times in between reading and writing blocks of data. By executing such tasks in a separate thread, you avoid blocking your main application thread unnecessarily.

Callable vs. Runnable

The Java Callable interface is similar to the Java Runnable interface, in that both of them represents a task that is intended to be executed concurrently by a separate thread.

A Java Callable is different from a Runnable in that the Runnable interface's run() method does not return a value, and it cannot throw checked exceptions (only RuntimeExceptions).

Additionally, a Runnable was originally designed for long running concurrent execution, e.g. running a network server concurrently, or watching a directory for new files. The Callable interface is more designed for one-off tasks that return a single result.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC