Thread pools (Executor Framework)

  1. Creating a new Thread for every job may create performance and memory problems,To overcome this problem we should go for Thread pool.
  2. Thread pool is a pool of already created Threads ready to do our job.
  3. Java 1.5 version introduces Thread pool framework to implement thread pools.
  4. Thread pool framework also know as executor framework.
  5. We can create a thread pool as follows
    ExecutorService service = Executors.newFixedThreadPool(int threadCount);
  6. We can submit a runnable job by using submit method
  7. We can shutdown executor service by using shutdown method
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) {
class MyRunnable implements Runnable{
	String name;
	MyRunnable(String name){ = name;
	public void run() {
		System.out.println("Thread execution started for "+name+" Thread Name : "+Thread.currentThread().getName());
		try {
		} catch (InterruptedException e) {
		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.

Reference :

Leave a Comment