ThreadPoolExecutor and BlockingQueue with an example

After Java 5 ThreadPoolExecutor changed the way of multi threading in Java . It was a nightmare to implement multi threading prior to Java 5 but with the help of ThreadPoolExecutor the situation has changed . I am going to explain how to use it and meaning of different fields of it .

Step 1 :Create a thread class .

package com.technotailor;
public class DemoThread implements Runnable 
    private String name = null;
    public DemoThread(String name) { = name;
    public String getName() {
    public void run() {
        try {
            System.out.println("Before sleep : " + name);
        } catch (InterruptedException e) {
        System.out.println("After sleep : " + name);

Step 2 : Let’s understand blocking queue now . If you remember any multi threading interview before Java 5 then Producer-consumer problem was the favorite question of any interviewer . By use of blocking queue you do not need to write any code for this, ThreadPoolExecutor put every thread in this queue as a worker until it got processor to run this thread . You can create object of blocking queue by giving it a size . Do not afraid by it’s name it is not blocking anything , It’s just keeping objects until processor is available to execution .

BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(50);

Step 3 : To create a thread pool executor object, you need to provide few values .

ThreadPoolExecutor executor = new ThreadPoolExecutor(5,20, 5000, TimeUnit.MILLISECONDS, blockingQueue);

Let’s understand them in sequence of their value in object creation .
Core pool size : First one is core pool size which we gave value as 5 above . Core pool size is the value that how many parallel threads will be running at one point of time .

Max pool size : Second one is max pool size . Max pool size is not useful in every case .There are two scenarios given below .
In first scenario, if in your functional requirement someone going to hit you with opening threads without looking for your capacity , then max pool size will help you . If someone is giving you thread on speed more then threads execution time and your blocking queue is full with having 50 threads in it then up to max pool size ThreadPoolExecutor will handle the request before rejecting it by throwing exception .
In second scenario if your functional requirement says that someone will only provide you objects or threads according to your capacity then remainingcapacity() method of blocking queue can help and max pool size will not be required .


Idle time and it’s unit : This is a time for which a thread will wait for a new worker(When we fire executorr.execute() method on one object it adds in blocking queue and become worker before it gets processor or any empty thread to run on ) to come before it will return to it’s pool .

Blocking queue object : We already know enough about it, still this is a queue where all worker waits for their task .

Step 4 : Lets run above thread class with these settings .

package com.technotailor;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class DemoExecutor 
    public static void main(String[] args) 
        Integer threadCounter = 0;
        BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(50);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10,
                                            20, 5000, TimeUnit.MILLISECONDS, blockingQueue);
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            public void rejectedExecution(Runnable r,
                    ThreadPoolExecutor executor) {
                System.out.println("DemoTask Rejected : "+ ((DemoThread) r).getName());
        while (true) {
            // Adding threads one by one
            System.out.println("Adding DemoTask : " + threadCounter);
            executor.execute(new DemoThread(threadCounter.toString()));

As you can see how easy it is to handle threads now . You just need to provide configuration rest is in hands of ThreadPoolEecutor .

For more information, see the Thread Pool Exeutor

Other related posts are :
Concept of AOP (Aspect oriented programming) every spring programmer use without knowing about it .
Set datasource spring bean properties dynamically if server is not available
Top 10 spring interview questions and their answers. Spring basic concepts.
HTML to PDF conversion in JAVA | HTML to PDF example in JAVA

Please share this posts on Facebook,Linkeedin,Google+,Twitter by clicking on below icons.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s