Tuesday, December 29, 2015

Callable Interface in Java

Callable Interface in Java

1) Runnable interface is older than Callable, there from JDK 1.0, while Callable is added on Java 5.0.

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

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

4) Another difference on run and call method is that run method can not throw checked exception, while call method can throw checked exception in Java.

java.util.concurrent.Callable has been introduced in JDK 5 . Callable is a thread that returns the result. There is a method call() in Callable interface that must be overridden for computation task.

To run Callable, submit() method of ExecutorService is used. ExecutorService also provides invokeAll() and invokeAny () method to run Callable threads.

To fetch the result of call() method of Callable interface, java provides Future class. ExecutorService.submit() method returns Future instance and then get() method of Future, returns the result of call() method of Callable..

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;

public class CallableDemo{
            public static void main(String[] args) throws InterruptedException,              ExecutionException {
                        ExecutorService service =Executors.newSingleThreadExecutor();
                        SumTask st=new SumTask(5);
                        Future<Integer> future=service.submit(st);
                        Integer result=future.get();
                        System.out.println(result);
            }
           
}

 class SumTask implements Callable<Integer>{

            private int num;
            public SumTask(int num) {
                        this.num=num;
            }

            @Override
            public Integer call() throws Exception {
                        int result = 0;
                        for(int i=1;i<=num;i++){
                                    result+=i;
                        }
                        return result;
            }
}


Output :

15

No comments:

Post a Comment