Callable And Future in Java

CALLABLE AND FUTURE IN JAVA

CALLABLE AND FUTURE in java are important concepts.

There are two ways for creating threads in java – one by extending the Thread class and other by creating a thread with a Runnable interface.
However, Runnable interface does not return result when it terminates, i.e. when run() completes executing it doest not return anything.
For supporting this feature, the Callable interface is present in Java.

DIFFERENCE BETWEEN CALLABLE AND RUNNABLE

For implementing Runnable, the run() method needs to be implemented which does not return anything,
while for Callable, the call() method needs to be implemented which returns a result on completion.
However thread can not be created with a Callable, it can only be created with a Runnable.
Another difference is that the call() method can throw an exception whereas run() method cannot throw exception.

Method signature that has to overridden for implementing Callable.

public Object call() throws Exception;

JAVA PROGRAM FOR CALLABLE IMPLEMENTATION
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class CallableExample implements Callable
{

public Object call() throws Exception
{
Random generator = new Random();

Integer randomNumber = generator.nextInt(5);

Thread.sleep(randomNumber * 1000);

return randomNumber;
}
}
FUTURE

When the call() method completes, return value must be stored in an object in main thread, so that the main thread can know about the result
that the thread returned. For this, a Future object can be used. It holds Future as an object as a result – it may not hold it right now.
but it will do so in the future (once the Callable returns). Thus, a Future is basically one way the main thread can keep track of the progress and result from other threads

Callable and Future do two different things – Callable is similar to Runnable, in that it encapsulates a task that is meant to run on another thread,
whereas a Future is used to store a result obtained from a different thread.

Methods of Future –

public boolean cancel(boolean mayInterrupt): Used to stop the task. It stops the task if it has not started. If it has started, it interrupts the task only if mayInterrupt is true.
public Object get() throws InterruptedException, ExecutionException: Used to get the result of the task. If the task is complete, it returns the result immediately, otherwise it waits till the task is complete and then returns the result.
public boolean isDone(): Returns true if the task is complete and false otherwise.

To create the thread, a Runnable is required. To obtain the result, a Future is required.

The Java library has the concrete type FutureTask, which implements Runnable and Future, combining both functionality conveniently.

A FutureTask can be created by providing its constructor with a Callable. Then the FutureTask object is provided to the constructor of Thread to create the Thread object. Thus, indirectly, the thread is created with a Callable. For further emphasis, note that there is no way to create the thread directly with a Callable.

import java.util.Random; 
import java.util.concurrent.Callable; 
import java.util.concurrent.FutureTask; 

class CallableExample implements Callable 
{ 

public Object call() throws Exception 
{ 
Random generator = new Random(); 
Integer randomNumber = generator.nextInt(4); 

Thread.sleep(randomNumber * 100); 

return randomNumber; 
} 

}
public class CallableFutureImpl 
{ 
public static void main(String[] args) throws Exception 
{ 
FutureTask[] randomNumberTasks = new FutureTask[5]; 

for (int i = 0; i < 5; i++) 
{ 
Callable callable = new CallableExample(); 

randomNumberTasks[i] = new FutureTask(callable); 

Thread t = new Thread(randomNumberTasks[i]); 
t.start(); 
} 

for (int i = 0; i < 5; i++) 
{ 
System.out.println(randomNumberTasks[i].get()); 

} 
} 
}
Output:

4
2
3
3
0

References

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

3 Comments

  1. I spent a lot of time to locate something similar
    to this

  2. Runnable is not the only way to get a thread. You can as well use an Executor with a thread pool then use submit() method to execute call() method of the Callable.

Leave a Reply