Monday, 15 May 2017

Difference between Callable and Runnable

The Callable interface is introduced in Java 5, however, Runnable interface is from JDK 1.0. Callable can return the result of an operation performed inside call() method, which was one of the limitations with the Runnable interface.

Another significant difference between Runnable and Callable interface is the ability to throw checked exception. The Callable interface can throw checked exception because its call method throws Exception.

Commonly FutureTask is used along with Callable to get the result of asynchronous computation task performed in call() method.

Callable vs Runnable interface
1) Runnable interface has run() method to define task while Callable interface uses call() method for task definition.

2) run() method does not return any value, it's return type is void while call method returns value. The Callable interface is a generic parameterized interface and Type of value is provided when an instance of Callable implementation is created.

3) Another difference on run and call method is that run method cannot throw checked exception while call method can throw checked exception.

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;
     }
    
     @Override
     public Integer call() throws Exception {
           int result = 1;
           for(int i=1;i<=num;i++){
                result*=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();

           System.out.println("Factorial of 10 is "+result);
     }
}



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...