How to create Thread Pool in Java using Executors framework?

Since JDK1.5 one new concurrency package called java.util.concurrent was introduced in Java. This new package has multiple concurrent utilities to protect and help Java applications in concurrent environment. Thread Pooling is one of them to boost threading performances. Thread Pool has multiple benefits in multi-threading application.

To understand Thread Pooling, you need to understand meaning of pooling. Pooling is one kind management of objects collection. This collection of objects, protect objects from garbage collection and reuse them to fulfill any specific purpose. Reusing live object is really good idea to save time and memory of application. For example, you might have use Connection Pooling to connect your application with database. Connection Pooling has same concept to reuse connection objects to connect with database every time.

Now it is time to know the advantages of Thread Pooling in concurrent application. A marginal amount of time of CPU is consumed to initializing and distorting to a thread. So it is good idea to reuse existing thread instead of creating new thread every time. Therefore Thread Pooling is solution of this problem. To create thread pool, you can create fixed number of worker threads in Pool and give these worker threads to a corresponding work or task to perform. Now fixed number of worker threads will finish their task and will get reading to accept new task to perform, until whole tasks get finished. Thread Pool will save big about of time of CPU as well as memory, by not to create and destroy threads every time. There is one more benefit of pooling is that, by creating Thread Pool, it is easy to manage number to threads for an application. You can control how many threads are safe for an application instead of creating too many threads without know application capability. You can create fixed number of threads in a pool instead of just creating countless threads in application. If your application is not able to control number of threads for your application, then it could be a cause of OutOfMemoryError.

Now you know what is Thread Pooling as well as benefits of Thread Pooling. But now question arise, how to create Thread Pool in Java? As I mentioned above, now Java has new concurrency package java.util.concurrent. This concurrency package has included, Executors framework to create and manage Thread Pool.

Here I would like to show you Java programming example to show you, how Thread Pool get created and how to manage them. In this example, there are two Thread Pools one is Producer and other is Consumer. Producer Thread Pool will produce some output and Consumer Thread Pool will consume that output. Both Thread Pools have fixed number of worker threads to perform given tasks. Now take a look to this coding example.

SharedPlace.java

/**
 * SharedPlace class is common shared place where Producer Thread Pool places its outputs
 * and Consumer Thread Pool fetch those outputs and consume them.
 *
 */

public class SharedPlace {

	private String text;

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public void remove() {
		this.text = null;
	}

	public boolean isEmpty() {
		return (this.text == null) ? true : false;
	}
}

Producer.java

/**
 * Producer class is actually Producer Thread Pool, which would produce some output
 * <code>String </code> and place this <code>String</code> to a Shared Place.
 */

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Producer {

	private SharedPlace sharedPlace;
	private final int COUNT;

	public Producer(SharedPlace sharedObj, int count) {
		this.sharedPlace = sharedObj;
		this.COUNT = count;
	}

	public void startProduction() {

		ExecutorService executorService = Executors.newFixedThreadPool(5);
		for (int i = 1; i <= COUNT; i++) {
			executorService.execute(new Task(i));
		}
		executorService.shutdown();
	}

	private class Task implements Runnable {

		private final int TASKNUM;

		public Task(int taskNum) {
			TASKNUM = taskNum;
		}

		public void run() {

			String str = "TASK-"+TASKNUM;

			synchronized (sharedPlace) {

				while (!sharedPlace.isEmpty()) {
					try {
						sharedPlace.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				sharedPlace.setText(str);
				sharedPlace.notifyAll();
			}

		}

	}

}

Consumer.java

/**
 * Consumer class is Consumer Thread Pool, who will fetch shared <code>String</code> objects from 
 * SharedPlace class and consume them.
 */

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Consumer {

	private final int COUNT;
	private final SharedPlace sharedPlace;
	private int workDone = 0;
	public Consumer(SharedPlace sharedObj, int count) {
		this.sharedPlace = sharedObj;
		this.COUNT = count;
	}

	public void startConsumption() {
		ExecutorService executorService = Executors.newFixedThreadPool(5);
		for (int i = 0; i < COUNT; i++) {
			executorService.execute(new Worker());
		}
		executorService.shutdown();
	}

	private class Worker implements Runnable {

		public void run() {

			synchronized (sharedPlace) {

				while (sharedPlace.isEmpty()) {
					try {
						sharedPlace.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				String text = sharedPlace.getText();
				sharedPlace.remove();
				workDone++;
				System.out.println("WORK DONE=" + workDone + " " + text);
				sharedPlace.notifyAll();
			}
		}
	}

}

ThreadPool.java

/**
 * ThreadPool class is initializer class which would initialize both 
 * Producer and Consumer Thread Pools and initiate their functioning.
 */

public class ThreadPool {

	public static void main(String[] args) {

		SharedPlace sharedObj = new SharedPlace();
		Producer producer = new Producer(sharedObj, 100);
		Consumer consumer = new Consumer(sharedObj, 100);
		producer.startProduction();
		consumer.startConsumption();

	}
}

Try this code and see how Thread Pool works in java. If you have any doubt or advise, please write and post your queries or comments below this blog. Hope this will help you.

Deals on Tablets, Get up to 25% off on Tablets - Dell, Lenovo, Samsung, HCL and others.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>