Thread pool in Java

Spread the love

thread pool is a pool threads that can be “reused” to execute tasks, so that each thread may execute more than one task. A thread pool is an alternative to creating a new thread for each task you need to execute.

We should take into consideration that there comes a lot of time and resource to create a thread increasing the I/O consumption. So to create a new thread for each task but be very expensive.

So the best thing would be to create a thread pool having a fixed pool of threads which would service all request which one.

You can consider the example of http requests handled by the jsp/servlet. Each request is treated as a task and there are threads which are handling those requests.

In java, a thread pool is provided by an executor service

Let’s look at an example.

import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;
  
class WorkerThread implements Runnable {  
    private String message;  
    public WorkerThread(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(2000);  } catch (InterruptedException e) { e.printStackTrace(); }  
    }  
} 

public class ThreadPoolTestMain {  
     public static void main(String[] args) {  

        //A thread pool of 20 threads is created.
        ExecutorService executor = Executors.newFixedThreadPool(10); \\line 3

        for (int i = 0; i < 20; i++) {  \\ line 4
            Runnable worker = new WorkerThread("" + i);  
            //Calling Execute Method Of ExecutorService  
            executor.execute(worker); \\ line 6
          }  
        executor.shutdown();  
        while (!executor.isTerminated())  \\ line 8
        {   
        }  
        System.out.println("Finished Executing all threads");  
    }  
 }  

If you look at the above example. a thread pool of 10 threads are created at line 3 by the executor service. Now the thread pool requires tasks.

At line 4, we create 20 kind of tasks and assign it to executor service to execute it.

Executor service’s Is terminated method is checked at line 8 to check for completion and if it returns true then the process completes.

Thanks for reading!!!!