Callable and Future in Java
In Java, Callable and Future are the two most important concepts that are used with thread. In this section, we will understand how we can use Callable and Future in our code.
Future is used for storing a result received from a different thread, whereas Callable is the same as Runnable in that it encapsulates a task that is meant to be run on another thread.
Let's understand each one of them one by one with an example:
Java offers two ways for creating a thread, i.e., by extending the Thread class and by creating a thread with a Runnable. There is a drawback of creating a thread with the Runnable interface, i.e., we cannot make a thread return result when it terminates, i.e., when the run() completes. In order to overcome this drawback, Java provides the Callable interface.
These are the two main differences between the Callable and Runnable methods:
Note: We can create a thread by using Runnable, not by using Callable.
The syntax of the call() method is as follows:
public Object call() throws Exception;
Let's take an example to understand how we can use Callable interface:
In the main() method, the returned value of the call() method(after completion) should be stored in an object to know about the result that the thread returns. In order to store the returned data in the main() method, we use a Future object.
The future is one of the ways through which we can keep track of the progress and result from other threads. We need to override the five methods for implementing the Future interface. The cancel(), get() and isDone() methods are the most important methods from the Future interface.
public boolean cancel(boolean mayInterrupt)
The cancel() method is used to stop the task if it has not started. If the task has started and the mayInterrupt boolean value is true, it will interrupt that task too.
public Object get() throws InterruptedException
The method returns the result of the task. It returns the result immediately if the task is completed; else, it will wait for its completion and then returns the result.
public boolean isDone() throws InterruptedException
It returns a boolean value based on the completion of the task.
Note: For creating a thread, a Runnable is necessary.
Note: For obtaining the result, a Future is necessary.
Let's take an example to understand how we can use Future to store the returned result of call() in the main() method:
Let's take another example in which we will use only the Runnable interface.