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) {
        this.name = name;
    }
 
    public String getName() {
        return this.name;
    }
 
    @Override
    public void run() {
        try {
            System.out.println("Before sleep : " + name);
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        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 .

if(blockingQueue.remainingCapacity()>0){}

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() {
            @Override
            public void rejectedExecution(Runnable r,
                    ThreadPoolExecutor executor) {
                System.out.println("DemoTask Rejected : "+ ((DemoThread) r).getName());
            }
        });
        while (true) {
            threadCounter++;
            if(executor.getQueue().remainingCapacity()===0){
            	break;
            }
            // 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.

Advertisements

Interview questions on concept of code on interface rather then class

Oops concept is always a must to have skill by an interviewee. Today i am going to explain interview question-answer and practical implementation of one oops concept which says Code on Interface rather then a Class.

Question1 : What does code on interface rather then class means.
Answer : This is an oops concept which says that we should call methods of a class with the reference of it’s interface rather then that class itself.

Question2 : Then interviewer asked what is the benefit of using interface reference .
Answer : I explained it with the help of example. If we have a restro-bar entity Which have both food items and drink items as its methods . When we go in restro bar and we want to drink then they will provide us two seperate menu for drink and eat(two interfaces), so that we can choose easily between drinks items(drink interface) and inspite of restrobar(class) have eat items too but it won’t bother me . So having two seperate interfaces made customer choose easily between items according to their concerns .


public interface DrinkMenu {
public List drinkItems();
}
public interface FoodMenu {
public List foodItems();
}

public class RestroBar{
public List drinkItems(){
List drinkItems=new ArrayList();
//add drink items
return drinkItems;
}
public List foodItems(){
List foodItems=new ArrayList();
//add food items
return foodItems;
}
}

Question 3 : Then interviewer asked me what if i want to order food from different restaurants daily but does not want to give different websites to order, how could i achieve this.
Answer : Now definitely he wants to understand if i can use interface practically and solve his problem. So i told him to solve this problem we need an interface having method which will return list of food items and different restaurants(Classes) will implement this method and will return filled list with their food items.

public interface Restaurants {
public List foodItems();
}
public class ChawlaRestaurant{
public List foodItems(){
List foodItems=new ArrayList();
//Chawla food items
return foodItems;
}
}
public class HaweliRestaurant{
public List foodItems(){
List foodItems=new ArrayList();
//Haweli food items
return foodItems;
}
}

Now we need a factory which will return Restaurants interface reference holding particular restaurant object by taking restaurant name as input.


public class ObjectFactory{
public Restaurants getRestaurantObject(String restaurantName){
Restaurants restaurants = //By using reflection we can create obect
return restaurants;
}
}

Now in main class which will be access by user we will get hotel name input from user then that restaurants object from factory at run time and then food items of that particular restaurant.


public class UserInput{
public class displayFoodItems(String restaurantName){
ObjectFactory objectFactory=new ObjectFactory();
Restaurants restaurants = objectFactory.getRestaurantObject(restaurantName);
List foodItems = restaurants.foodItems();
for(String foodItem : foodItems){
system.out.println(foodItem);
}
}
}

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Top 10 spring interview questions and their answers. Spring basic concepts.
Logback logs are not working. Log4j logs are not working. Steps to make logging work.
MQ connection not closed and giving MQ Error-2009

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