Provide Best Programming Tutorials

The Callable & Future Interface

By implementing the Runnable interface we can start a new thread, but unfortunately, this method doesn’t return a value. So if we want the thread to have return value then we can use the Callable interface. This interface has a method called call() and it returns use Generic to define the return type of Object.

Java Callable

Java Callable interface uses Generic to define the return type of Object. Executors class provide useful methods to execute Java Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object.

Java Future

Java Callable tasks return java.util.concurrent.Future object. Using Java Future object, we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.

Java Future provides cancel() method to cancel the associated Callable task. There is an overloaded version of get() method where we can specify the time to wait for the result, it’s useful to avoid current thread getting blocked for a longer time. There are isDone() and isCancelled() methods to find out the current status of an associated Callable task.

Here is a simple example of Java Callable task that returns the name of the thread executing the task after one second. We are using the Executor framework to execute 100 tasks in parallel and use Java Future to get the result of the submitted tasks.

package multithreading.createNewThread;

import java.util.concurrent.*;


public class CallableDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Future<Double> future = executorService.submit(new PrintNumber());
        executorService.shutdown();
        while (!future.isDone()) {

        }
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class PrintNumber implements Callable<Double> {
    @Override
    public Double call() throws Exception {
        Thread.sleep(3000);
        return Math.random();
    }
}

Once we execute the program it will display a random double number on the console 3 seconds later.

 

Leave a Reply

Close Menu