Thread Pooling using Executors and ThreadPoolExecutor in Java

Thread Pool manages pool of threads waiting for job. They are called worker Threads.Initially threads are waiting in pool for job and once they will get job to process, it will be process that job and move back to thread pool and wait for another job.

As mentioned in below example, I have create fixed size of Thread Pool with 5 worker threads. Now I will submit 10 jobs which should be processed by worker threads in Thread Pool. But Since I have only 5 Threads available in Thread pool, how it will work?


Let's See :
  • Even though we have submit 10 jobs and we have only 5 worker thread. 5 jobs will be processed by available worker threads. Mean while, remaining other 5 jobs  will wait.
  • As soon as one of job finishes,thread move back to thread pool and waiting for job. So another job from wait queue will be picked up by worker thread and it will be executed.
  • Refer to output of Thread Pooling example as below.

In java.util.concurrent package, there is interface called ExecutorService which extend Executor Interface.Class Executors provides factory,utility methods for Executor,ExecutorService etc.

Class Executors provides simple implementation of ExecutorService using ThreadPoolExecutor.
Job of ThreadPoolExecutor is to execute submitted task using available worker thread.

Thread Pooling Java Program using Executors and ThreadPoolExecutor :
package com.anuj.threading;

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

/**
 * ThreadPool Example
 * ExecutorService and Executors
 * @author Anuj
 *
 */
public class ThreadPoolExample extends Thread{

 int jobId;
 
 public ThreadPoolExample(int id) {
  this.jobId = id;  
 }
 
 @Override
 public void run() {
  String currentThread = Thread.currentThread().getName();
  System.out.println(currentThread + " Thread Start" + " Job Id-"+jobId);
  
  try {
   Thread.sleep(500);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  
  System.out.println(currentThread + " End ");
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  ExecutorService executor = Executors.newFixedThreadPool(5);
  
  for(int i=0;i<10;i++){
   Runnable r = new ThreadPoolExample(i);
   executor.execute(r);
  } 
  executor.shutdown();
  while(!executor.isTerminated()){   
  }
 }

}

Output:
pool-1-thread-2 Thread Start Job Id-1
pool-1-thread-3 Thread Start Job Id-2
pool-1-thread-1 Thread Start Job Id-0
pool-1-thread-4 Thread Start Job Id-3
pool-1-thread-5 Thread Start Job Id-4
pool-1-thread-2 End
pool-1-thread-2 Thread Start Job Id-5
pool-1-thread-3 End
pool-1-thread-3 Thread Start Job Id-6
pool-1-thread-1 End
pool-1-thread-1 Thread Start Job Id-7
pool-1-thread-4 End
pool-1-thread-4 Thread Start Job Id-8
pool-1-thread-5 End
pool-1-thread-5 Thread Start Job Id-9
pool-1-thread-2 End
pool-1-thread-3 End
pool-1-thread-5 End
pool-1-thread-4 End
pool-1-thread-1 End

No comments:

Post a Comment