Thread Pools in Java



A thread pool is a collection of pre-initialized threads. The general plan behind a thread pool is to form variety of threads at method startup and place them into a pool, wherever they sit and expect work. once a server receives a call for participation, it awakens a thread from this pool—if one is available—and passes it the request for service. Once the thread completes its service, it returns to the pool and awaits a lot of work. If the pool contains no accessible thread, the server waits till one becomes free.

It saves time as a result of there's no need to produce new thread.

It is utilized in Servlet and JSP wherever instrumentality creates a thread pool to method the request.

Example

EmployeeThread.java

importjava.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class EmployeeThread implements Runnable {
   private String message;
   public EmployeeThread(String s) {
      this.message=s;
   }
   public void run() {
      System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);
      processmessage();//call processmessage method that sleeps the thread for 2 seconds
      System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name
   }
   private void processmessage() {
      try { Thread.sleep(1000);
      }
      catch (InterruptedException e){
         e.printStackTrace(); }
   }
}

ExampleThreadPool.java

public class implementThreadPool {
   public static void main(String[] args) {
      ExecutorService executor = Executors.newFixedThreadPool(6); //creating a pool of 6 threads
      for (int m = 0; m< 6; m++) {
         Runnable worker = new EmployeeThread("" + i);
         executor.execute(worker); //calling execute method of ExecutorService
      }
      executor.shutdown();
      while (!executor.isTerminated()) { }
      System.out.println("Finished all the threads");
   }
}

Advertisements