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
public interface Callable<v> {
V call() throws Exception;

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.
 <T> Future<T> submit(Callable<T> task);
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.


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.
package org.arpit.java2blog;
import java.util.concurrent.Callable;
public class PowerCalc implements Callable<Double>{
private double number;
 PowerCalc(double number)

public Double call() throws Exception {
System.out.println("Calculating Square with "+Thread.currentThread().getName());
  return Math.pow(number, number);

Create another class called FactorialCalc which implements Callable interface.
package org.arpit.java2blog;
import java.util.concurrent.Callable;
public class FactorialCalc implements Callable<Double> {
private double number; FactorialCalc(double number) {
public Double call() throws Exception {
this.number = number; } @Override System.out.println("Calculating factorial with "+Thread.currentThread().getName()); Thread.sleep(5000); double fact = 1; for (int i = 2; i <= number; i++) { fact *= i; } return fact; } }
Now create a main classed named
package org.arpit.java2blog;

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

public class FutureCallableMain {

ExecutorService es=Executors.newFixedThreadPool(4);
public static void main(String[] args) {
  System.out.println("Start : ");
  Future<Double> powerFuture20;

powerFuture20=es.submit(new PowerCalc(20));
Future<Double> factorialFuture20;
  Future<Double> powerFuture25;
  Future<Double> factorialFuture25;

factorialFuture25=es.submit(new FactorialCalc(25));
factorialFuture20=es.submit(new FactorialCalc(20));
  powerFuture25=es.submit(new PowerCalc(25));
   try {
System.out.println("Square of "+25+" : "+powerFuture25.get());
System.out.println("Square of "+20+" : "+powerFuture20.get());
    System.out.println("Factorial of "+20+" : "+factorialFuture20.get());

System.out.println("Factorial of "+25+" : "+factorialFuture25.get());
   } catch (InterruptedException | ExecutionException e) {

When you run above program, you will get below output:
Start : 
Calculating Square with pool-1-thread-1
Calculating factorial with pool-1-thread-2
Calculating Square with pool-1-thread-3
Square of 20 : 1.048576E26
Calculating factorial with pool-1-thread-4
Factorial of 20 : 2.43290200817664E18
Square of 25 : 8.881784197001253E34
Factorial of 25 : 1.5511210043330986E25
As you can see, we are able to execute 4 tasks concurrently which return square and Factorial of 20 and 25.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012