Java — Callable and Future | Code Factory

  • 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;
}
}
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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Going small — Leaving the Microsoft Nest

CS373 Fall 2020: Stephen Zheng

DevOps Expectations

Keeping secrets out of Git in your iOS app

Sharing a quick survey result of GraphQL server usage in Japan

Pie chart of GraphQL usage

Web App Development & Advantages — Everything You Need to Know.

Save hours by organizing your CSS

Good Programmers are Good at the Command Line.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

How to find max number in an array using tail recursion in java

Immutable behavior of Java String

Print a sequence using 3 threads | Java

First Step to Tune gRPC in Java