In my Previous Blog I covered the basics of Multithreading in Java. to read that blog. Click here The previous Blog covered how to create Threads by Extending the Thread class and implementing the Runnable Interface. This article will be covering 2 topics. Creating Threads by implementing the Callable Interface Using the Executor Framework in Java Implementing the Callable Interface In order to create a Piece of code which can be run in a Thread, we create a class and then implement the Interface. The task being done by this piece of code needs to be put in the function. In the below code you can see that is a class which implements Interface, and the task of summing up numbers from 0 to 4 is being done in the function. Callable call() CallableTask Callable java.util.concurrent.Callable; { { sum = ; ( i = ; i < ; i++) { sum += i; } sum; } } import < > class CallableTask implements Callable Integer @Override Integer Exception public call () throws int 0 for int 0 5 return In the above code you would notice that has a parameter of . This shows that the return type of this Callable will be Integer. Also it can be seen that the call function returns type. Callable Integer Integer Creating the Threads and running them The code below shows how to create the Threads and then run them. java.util.concurrent.ExecutionException; java.util.concurrent.FutureTask; { { FutureTask<Integer>[] futureList = FutureTask[ ]; ( i = ; i <= ; i++) { Callable<Integer> callable = CallableTask(); futureList[i] = FutureTask<Integer>(callable); Thread t = Thread(futureList[i]); t.start(); } ( i = ; i <= ; i++) { FutureTask<Integer> result = futureList[i]; { System.out.println( + i + + result.get()); } (InterruptedException e) { e.printStackTrace(); } (ExecutionException e) { e.printStackTrace(); } } } } import import public class CallableInterfaceDemo public static void main (String[] args) new 5 for int 0 4 new new new for int 0 4 try "Future Task" ":" catch catch In order to create a Thread, first we need to create an Instance of which implements the Interface as shown in CallableTask Callable Callable<Integer> callable = new CallableTask(); Then we need to create an Instance of the class and pass the instance of task as an argument as shown in FutureTask Callable futureList[i] = new FutureTask<Integer>(callable); Then to create a Thread we create an instance of the class and pass the Instance of the class as an argument as shown in Thread FutureTask Thread t = new Thread(futureList[i]); Finally the Thread is started with the function. start() Getting the result from the Thread In case of Callables the Thread can actually . In order to get this value we can call the function on the instance of the . In our code, the return value of the thread is the sum of numbers from 0 to 4. return a value get() FutureTask This is shown in the below code snippet FutureTask<Integer> result = futureList[i]; { System.out.println( + i + + result.get()); } (InterruptedException e) { e.printStackTrace(); } (ExecutionException e) { e.printStackTrace(); } try "Future Task" ":" catch catch Also the thread may throw an as well which can be handled with blocks. Exception try catch Complete Code Here is the complete code discussed till now java.util.concurrent.Callable; java.util.concurrent.ExecutionException; java.util.concurrent.FutureTask; { { sum = ; ( i = ; i < ; i++) { sum += i; } sum; } } { { FutureTask<Integer>[] futureList = FutureTask[ ]; ( i = ; i <= ; i++) { Callable<Integer> callable = CallableTask(); futureList[i] = FutureTask<Integer>(callable); Thread t = Thread(futureList[i]); t.start(); } ( i = ; i <= ; i++) { FutureTask<Integer> result = futureList[i]; { System.out.println( + i + + result.get()); } (InterruptedException e) { e.printStackTrace(); } (ExecutionException e) { e.printStackTrace(); } } } } import import import < > class CallableTask implements Callable Integer @Override Integer Exception public call () throws int 0 for int 0 5 return public class CallableInterfaceDemo public static void main (String[] args) new 5 for int 0 4 new new new for int 0 4 try "Future Task" ":" catch catch The Executor Framework Creating a Thread on the Fly everytime is Resource Intensive. One good alternative for this is to have some Threads already setup and then allocate our tasks to these threads. This is where the Executors Class and ExecutorService are very useful. The above image shows a Thread pool with 4 threads. Whenever we want any task to be run, we can assign it to these threads. Once the task is complete, the Thread will be freed to take up other tasks. How to use the Executor Framework Here is a code which uses the Executor framework. java.util.concurrent.Callable; java.util.concurrent.ExecutionException; java.util.concurrent.ExecutorService; java.util.concurrent.Executors; java.util.concurrent.Future; { { sum = ; ( i = ; i < ; i++) { sum += i; } sum; } } { { ExecutorService executors = Executors.newFixedThreadPool( ); Future<Integer>[] futures = Future[ ]; Callable<Integer> w = Worker(); { ( i = ; i < ; i++) { Future<Integer> future = executors.submit(w); futures[i] = future; } ( i = ; i < futures.length; i++) { { System.out.println( + i + + futures[i].get()); } (InterruptedException e) { e.printStackTrace(); } (ExecutionException e) { e.printStackTrace(); } } } { executors.shutdown(); } } } import import import import import < > class Worker implements Callable Integer @Override Integer Exception public call () throws int 0 for int 0 5 return public class ExecutorDemo public static void main (String[] args) 4 new 5 new try for int 0 5 for int 0 try "Result from Future " ":" catch catch finally First we create a Class which and does the task which we need. Worker implements Callable Next we need to create an . ExecutorService The class has multiple implementations of the . Executors ExecutorService Let us use the class to create a fixed Thread pool of size 4. This is done as follows Executors ExecutorService executors = Executors.newFixedThreadPool(4); Next we need to submit our task to the Executor Service. This is done using the following Line of code Future<Integer> future = executors.submit(w); On submitting the task we get an Instance of the Object. The Future Object is what will store the result of the Task. Future Getting the result of the Thread In order to get the result of each task, we can call the method of the Instance. This is shown in the below code snippet. get() Future { System.out.println( + i + + futures[i].get()); } (InterruptedException e) { e.printStackTrace(); } (ExecutionException e) { e.printStackTrace(); } try "Result from Future " ":" catch catch The thread can also Throw an Exception which can be handled using . try catch Some possible Scenarios of the Fixed Thread Pool In this example we created a fixed Thread pool of size 4 If we submit a total of 3 tasks to this ExecutorService, then all 3 tasks will be assigned to the thread pool and they will start executing. If we submit 4 tasks to this ExecutorService, then again all 4 tasks will be assigned to the thread pool and they will start executing. Now if we submit 5 tasks to this thread pool. Only 4 of the tasks will be assigned to the thread pool. This is because the size of the Thread pool is 4. The 5th Task will be assigned only when one of the threads in the pool gets freed Shutting down the ExecutorService The ExecutorService needs to be shutdown when the threads are not needed anymore. This will ensure that the JVM is not consuming Additional Resources. The ExecutorService can be shutdown using the following command executors.shutdown(); It can be seen that this shutdown is put within the block. This is to ensure that the shutdown is always executed at the end of the code even if any exception occured. finally If the shutdown is not done in the right way, then in case any exception occurs then the ExecutorService will still be running and will be consuming Additional JVM resources. Code All the code discussed in this article can be found in this git repo Congrats😃 Now you know the following concepts Using the Callable InterfaceUsing the Java Executor Framework for Multithreading. In my future Articles I will be covering more topics on Multithreading In Order to read Similar Articles you can visit my Website Feel free to connect with me in or follow me in https://adityasridhar.com/ LinkedIn Twitter