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.

Concept of AOP (Aspect oriented programming) every spring programmer use without knowing about it .

Many of spring programmer these days, when it’s comes to AOP (Aspect oriented programming) says heard about it but never used it . It’s interesting to see that many of them use it without knowing about it . One of the example that most of us used is spring declarative transaction management annotation. We do know what @transactional annotation does but we do not know and doesn’t even care about how it is doing it ? Spring is using AOP here .

Let’s understand how AOP actually works . Well in theory when one bean(java object) call method of another bean then spring create a proxy between them . If there is an interface for that bean and coding is on that interface than it will work as proxy otherwise spring will create a proxy for it . This proxy can be programmed through AOP and we can code if we want to do something before method call,after method call,after exception throw etc .

Now let’s see how this theory works in actual . Let’s create one custom annotation like @transactional to understand it better .

Step 1 : To work AOP with spring we need to define

<aop:aspectj-autoproxy>

in custom-config.xml .

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:aop="http://www.springframework.org/schema/aop"        xmlns:mvc="http://www.springframework.org/schema/mvc"        xsi:schemaLocation="            http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.1.xsd            http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

  <!-- Scans for application @Components to deploy -->
    <context:annotation-config/>
  <context:component-scan base-package="com.stevenlanders.*" />

  <!-- enable AOP -->
  <aop:aspectj-autoproxy/>

</beans>

Step 2 : Create you custom annotation .

@Retention(RetentionPolicy.RUNTIME)
public @interface LogDuration {
   String value();
}

Step 3 : Write your AOP class. To do it, You need to use @Aspect annotation on that class . Then you need to create advice in this class. To do so, You need to choose one of the annotation given below .
@Before – Run before the method execution
@After – Run after the method returned a result
@AfterReturning – Run after the method returned a result, intercept the returned result as well.
@AfterThrowing – Run after the method throws an exception
@Around – Run around the method execution, combine all three advices above.
We are going to choose @Around here as we need to start and stop timer before and after of this method execution .

@Aspect
public class AopExample{

    //for any method with @LogDuration, no matter what the return type, name, or arguments are, call this method
    @Around("execution(@com.stevenlanders.annotation.LogDuration * *(..)) && @annotation(logDurationAnnotation)")
    public Object logDuration(ProceedingJoinPoint joinPoint, LogDuration logDurationAnnotation) throws Throwable {

        //capture the start time
        long startTime = System.currentTimeMillis();

        //execute the method and get the result
        Object result = joinPoint.proceed();

        //capture the end time
        long endTime = System.currentTimeMillis();

        //calculate the duration and print results
        long duration = endTime - startTime;
        System.out.println(logDurationAnnotation.value()+": "+duration+"ms"); //you should use a logger  

        //return the result to the caller
        return result;
    }

}

Step 4 : Put your annotation on methods for which you want to print execution time .

@Controller
public class ExampleController{

     @RequestMapping("/api/example/hello")
     @LogDuration("Hello World API")
     public @ResponseBody String getHelloWorld(){
          try {
            Thread.sleep(3000);
          } catch (InterruptedException e) {
            throw new RuntimeException("Sleep Interrupted", e);
          }
          return "Hello World";
     } 

}

Step 5 : Run this code .

Hello World API: 3002ms

For more information, see the Spring AOP Documentation

Other related posts are :
Interview questions on concept of code on interface rather then class
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.

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