Java — Callable and Future | Code Factory

Code Factory
2 min readJun 5, 2020

--

Index Page : Link

Donate : Link

WordPress Blog : Link

  • In the case of Runnable job Thread wouldn’t return anything after completing a job.
  • If a thread is require to return some result after execution then we should go for Callable.
  • Callable interface contains only 1 method call().
Object call() throws Exception
  • If we submit Callable object to Executor then after completing the job thread returns an Object of the type Future.
  • That is Future object can be used to retrieve the result from Callable job.
package com.example.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;
/**
* @author code.factory
*
*/
public class CallableTest {
public static void main(String... args) throws InterruptedException, ExecutionException {
MyCallable jobs[] = {
new MyCallable(10),
new MyCallable(20),
new MyCallable(30),
new MyCallable(40),
new MyCallable(50),
new MyCallable(60),
};
ExecutorService service = Executors.newFixedThreadPool(3);
for(MyCallable job : jobs) {
Future f = service.submit(job);
System.out.println(f.get());
}
service.shutdown();
}
}
class MyCallable implements Callable {
int no;
public MyCallable(int no) {
this.no = no;
}

public Object call() throws Exception {
System.out.print(Thread.currentThread().getName() + " sum of first " + no + " numbers : ");
int sum = 0;
for(int i=0; i<no; i++) {
sum = sum + i;
}
return sum;
}
}

Output :

pool-1-thread-1 sum of first 10 numbers : 45
pool-1-thread-2 sum of first 20 numbers : 190
pool-1-thread-3 sum of first 30 numbers : 435
pool-1-thread-1 sum of first 40 numbers : 780
pool-1-thread-2 sum of first 50 numbers : 1225
pool-1-thread-3 sum of first 60 numbers : 1770

--

--