JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Java ExecutorService example using Callable and Future

Callable interface represents a thread that can return a value. It is very much similar to Runnable interface except that it can return a value. Callable interface can be used to compute status or results that can be returned to invoking thread. For example: Let’s say you want to perform factorial and square of some numbers, you can do it concurrently using callable interface which will return value too. Callable defines only one method as below
You can define the task which you want to perform inside call method. If it executes successfully, call method will return the result else it must throw an exception. You can use ExecutorService’s submit to execute Callable task. Let’s see Signature of submit method in ExecutorService.
If you notice, return type of submit method is Future.
Future is generic interface that represents value which will be returned by callable interface. As callable will return value in some future time, name seems suitable here.
There are two methods to get actual value from Future.
get() : When this method is called, thread will wait for result indefinitely.
V get(long timeout, TimeUnit unit) : When this method is called, thread will wait for result only for specified time.

Example:

This program will demonstrate use of Callable and Future. We will create one callable for calculation of square and one callable for factorial. We will submit four tasks to ExecutorService for calculation of square and factorial of 20 and 25. This program will demonstrate how can you make use of Callable and Future to execute it concurrently.
Create class called PowerCalc which implements Callable interface.
Create another class called FactorialCalc which implements Callable interface.

 
Now create a main classed named FutureCallableMain.java.
When you run above program, you will get below output:
As you can see, we are able to execute 4 tasks concurrently which return square and Factorial of 20 and 25.

.