ThreadPool or Executor Framework
Creating a new Thread for every job may create a performance and memory problem, to overcome this we should go for the thread pool.
Thread pool is a pool of already created thread ready to do our job.
Java 1.5 version introduces a thread pool framework to implement a thread pool.
we can create a thread pool as follows-
ExecutorService service=Executors.newFixedThreadPool(3);//int nthreads
we can submit a Runnable job by using submit method-
service.submit(job);
we can shutdown an executor service by using shutdown methods-
service.shutdown();
The main advantage of this approach is a constant number of threads can be used to complete a job so a single thread can be used multiple times.
Let’s see the working examples:(using 3 threads to perform 6 jobs, so a single thread can be reused for multiple jobs ).
Runnable Interface:
package com.multithreading;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ExecutorDemo {public static void main(String[] args) {MyclassDemo [] jobs= {new MyclassDemo("Job1"), new MyclassDemo("Job2"), new MyclassDemo("Job3"), new MyclassDemo("Job4"), new MyclassDemo("Job5"), new MyclassDemo("Job6")};ExecutorService service=Executors.newFixedThreadPool(3); for(MyclassDemo job:jobs) { service.submit(job); }service.shutdown();}}class MyclassDemo implements Runnable{String name;public MyclassDemo(String name) {this.name=name;}@Overridepublic void run() {System.out.println(name+"... Job started by Thread"+Thread.currentThread().getName());try {Thread.sleep(1000);}catch (InterruptedException e) {}System.out.println(name+"... Job completed by Thread"+Thread.currentThread().getName());}}
Output:
Job2... Job started by Threadpool-1-thread-2
Job3... Job started by Threadpool-1-thread-3
Job1... Job started by Threadpool-1-thread-1
Job2... Job completed by Threadpool-1-thread-2
Job3... Job completed by Threadpool-1-thread-3
Job4... Job started by Threadpool-1-thread-2
Job5... Job started by Threadpool-1-thread-3
Job1... Job completed by Threadpool-1-thread-1
Job6... Job started by Threadpool-1-thread-1
Job4... Job completed by Threadpool-1-thread-2
Job5... Job completed by Threadpool-1-thread-3
Job6... Job completed by Threadpool-1-thread-1
Note:
While designing Webservers(web server is meant to serve static pages e.g. HTML and CSS. eg-Apache, Microsoft’s Internet Information Server (IIS) and Nginx — pronounced engine X) and Application servers(hosts and exposes business logic and processes, eg- JBOSS, Glassfish, Weblogic) we can use thread pool concept.
Callable Interface(using Future):
In the case of a Runnable job, the thread is not required to return anything after completing the job.
If a thread is required to return some result after completing of job then we should go for callable.
The Callable interface contains only one method call();
public Object call() throws Exception
If we submit the callable object to the executor then after completing the job the thread returns an object of type future. The future object can be used to retrieve the result from the callable job.
Let’s see the working examples:(using 3 threads to perform 8jobs, so a single thread can be reused for multiple jobs using callable and getting the result back).
package com.multithreading;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;public class ExecutorDemoCallable {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), new MyCallable(70), new MyCallable(80)};ExecutorService service=Executors.newFixedThreadPool(3);for(MyCallable job:jobs) {Future<Object> future=service.submit(job);System.out.println(future.get());}service.shutdown();}}class MyCallable implements Callable<Object>{int num;public MyCallable(int num) {this.num=num;}@Overridepublic Object call() throws Exception {System.out.println(Thread.currentThread().getName()+"... responsible to find the sum of first "+num+" numbers");int sum=0;for(int i=1;i<=num;i++)sum+=i;return sum;}}
Output:
pool-1-thread-1... responsible to find the sum of first 10 numbers55pool-1-thread-2... responsible to find the sum of first 20 numbers210pool-1-thread-3... responsible to find the sum of first 30 numbers465pool-1-thread-1... responsible to find the sum of first 40 numbers820pool-1-thread-2... responsible to find the sum of first 50 numbers1275pool-1-thread-3... responsible to find the sum of first 60 numbers1830pool-1-thread-1... responsible to find the sum of first 70 numbers2485pool-1-thread-2... responsible to find the sum of first 80 numbers3240
NOTE: Runnable Interface present in java.lang package and Callable Interface present in java.util.concurrent package.
Thank you for reading.