Monday, 15 May 2017

Callable example

java.util.concurrent.Callable has been introduced in JDK 5. Callable is a thread that returns the result. method
We need to implement(override) the call() of Callable interface for task computation and submit() method of ExecutorService can be used to run Callable.
To fetch the result of call() method of the Callable interface, ExecutorService.submit() method returns a Future instance and using the get() method of Future, we can fetch the result of call() method of Callable.

ExecutorService also provides invokeAll() and invokeAny() method to run Callable threads.

Java Future
As 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 the longer time. There are isDone() and isCancelled() methods to find out the current status of the associated Callable task.

Callable Example in Java
package com.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class CallableTask implements Callable<Integer> {
     private int num = 0;
     public CallableTask(int num){
           this.num = num;
     public Integer call() throws Exception {
           int result = 1;
           for(int i=1;i<=num;i++){
           return result;

 * Calculate the Factorial using callable.
 * @author rajesh dixit
public class CallableDemo {
     public static void main(String[] args) throws InterruptedException, ExecutionException {
           ExecutorService service =  Executors.newSingleThreadExecutor();
           CallableTask sumTask = new CallableTask(10);
           Future<Integer> future = service.submit(sumTask);
           Integer result = future.get();

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...