Java Thread Pools


Java Thread Pools consist of worker threads. A thread pool is a group of pre-instantiated, idle threads which are ready to be given work and provide a solution to the problem of thread cycle overhead.

Using worker threads minimizes the overhead due to thread creation.

 

The fixed thread pool is one of the common types of the thread pool. A thread is taken from the thread pool to assign a job through a service provider. When the thread job is completed after that it remains in thread pool for future use.


Advantage

Its performance is good because of no need to create a new thread. So it saves more time.


Example:

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
  
class Task implements Runnable    
{ 
    private String name; 
    public Task(String s) 
    { 
        name = s; 
    } 
    public void run() 
    { 
        try
        { 
            for (int i = 0; i<=2; i++) 
            { 
                if (i==0) 
                { 
                    System.out.println("Initialization "+Thread.currentThread().getName()
                            + " task name - "+ name +" " );    
                    //prints the Thread initialization  for every task  
                } 
                else
                {  
                    System.out.println("Executing "+Thread.currentThread().getName()
                    +" task name - "+ name +" " );    
                    // prints the Thread execution for every task  
                } 
                Thread.sleep(1000); 
            } 
            System.out.println(name+" complete"); 
        } 
        catch(InterruptedException e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 
public class ThreadPool
{         
    public static void main(String[] args) 
    { 
        // creates four tasks 
        Runnable r1 = new Task("task 1"); 
        Runnable r2 = new Task("task 2"); 
        Runnable r3 = new Task("task 3"); 
        Runnable r4 = new Task("task 4");
        // creates a thread pool and threads as the fixed pool size
        ExecutorService es = Executors.newFixedThreadPool(2);   
        // passes the Task objects to the pool to execute  
        es.execute(r1); 
        es.execute(r2); 
        es.execute(r3); 
        es.execute(r4);  
        // pool shutdown
        es.shutdown();     
    } 
} 

Real-time Usage

Java Thread Pool is used in Servlet and JSP. It creates a thread pool to process the request.





OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.