- Creating a new Thread for every job may create performance and memory problems,To overcome this problem we should go for Thread pool.
- Thread pool is a pool of already created Threads ready to do our job.
- Java 1.5 version introduces Thread pool framework to implement thread pools.
- Thread pool framework also know as executor framework.
- We can create a thread pool as follows
ExecutorService service = Executors.newFixedThreadPool(int threadCount); - We can submit a runnable job by using submit method
service.submit(job) - We can shutdown executor service by using shutdown method
service.shutdown()
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorFrameworkDemo {
public static void main(String[] args) {
MyRunnable[] jobArray = {
new MyRunnable("Tyson"),
new MyRunnable("Justin"),
new MyRunnable("Martin"),
new MyRunnable("Jake"),
new MyRunnable("Fade"),
new MyRunnable("Luke")
};
ExecutorService service = Executors.newFixedThreadPool(3);
for(MyRunnable job : jobArray) {
service.submit(job);
}
service.shutdown();
}
}
class MyRunnable implements Runnable{
String name;
MyRunnable(String name){
this.name = name;
}
public void run() {
System.out.println("Thread execution started for "+name+" Thread Name : "+Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread execution completed for "+name);
}
}
- In the above example three threads are responsible to execute six jobs so that a single thread can be reused for multiple jobs
- Note : While designing web servers and application servers we can use thread pool concept.