ThreadPoolExecutor

ThreadPoolExecutorThreadPoolExecutor is a class in the java.util.concurrent package that provides a highly customizable thread pool. It extends AbstractExecutorService and implements ExecutorService. This class allows you to configure various parameters like the number of threads, queue size, and rejection policies to control how tasks are executed.

Constructors

1. Primary Constructor

This is the most commonly used and flexible constructor:

public ThreadPoolExecutor(
    int corePoolSize,
    int maximumPoolSize,
    long keepAliveTime,
    TimeUnit unit,
    BlockingQueue<Runnable> workQueue
)Code language: HTML, XML (xml)

2. Extended Constructor with Custom ThreadFactory

public ThreadPoolExecutor(
    int corePoolSize,
    int maximumPoolSize,
    long keepAliveTime,
    TimeUnit unit,
    BlockingQueue<Runnable> workQueue,
    ThreadFactory threadFactory
)Code language: HTML, XML (xml)

3. Full Constructor with Rejection Policy

public ThreadPoolExecutor(
    int corePoolSize,
    int maximumPoolSize,
    long keepAliveTime,
    TimeUnit unit,
    BlockingQueue<Runnable> workQueue,
    ThreadFactory threadFactory,
    RejectedExecutionHandler handler
)Code language: HTML, XML (xml)

 Parameters from above constructors

  • corePoolSize: Minimum number of threads to keep in the pool.

  • maximumPoolSize: Maximum number of threads allowed.

  • keepAliveTime: Time to keep extra threads (above core) alive when idle.

  • unit: Time unit for keepAliveTime (e.g., TimeUnit.SECONDS).

  • workQueue: Queue used for holding tasks before execution (e.g., ArrayBlockingQueue, LinkedBlockingQueue).

  • threadFactory: Lets you create custom threads with names, priorities, etc.
  • handler: Specifies the policy for handling tasks that cannot be executed when the pool is saturated

ThreadPoolExecutor Methods in Java

The ThreadPoolExecutor class provides a wide range of control, monitoring, and customization methods for thread pool management. It extends AbstractExecutorService and implements the ExecutorService interface.

Below are its major methods grouped by functionality:

1. Task Execution

Method Description
void execute(Runnable command) Executes the given task (from Executor interface).
<T> Future<T> submit(Callable<T> task) Submits a task that returns a result.
<T> Future<T> submit(Runnable task, T result) Submits a task and returns a result upon completion.
Future<?> submit(Runnable task) Submits a task that returns null upon completion.

2. Lifecycle Management

Method Description
void shutdown() Initiates an orderly shutdown, finishing already submitted tasks.
List<Runnable> shutdownNow() Attempts to stop all actively executing tasks and returns a list of queued ones.
boolean isShutdown() Returns true if shutdown has been initiated.
boolean isTerminated() Returns true if the executor is completely terminated.
boolean awaitTermination(long timeout, TimeUnit unit) Blocks until all tasks complete or timeout occurs.

3. Pool Size and Thread Management

Method Description
int getPoolSize() Returns current number of threads in the pool.
int getActiveCount() Number of threads actively executing tasks.
int getCorePoolSize() Gets the core pool size.
void setCorePoolSize(int size) Sets the core pool size.
int getMaximumPoolSize() Gets the max pool size.
void setMaximumPoolSize(int size) Sets the max pool size.
long getKeepAliveTime(TimeUnit unit) Gets idle time before threads are terminated.
void setKeepAliveTime(long time, TimeUnit unit) Sets idle time before terminating idle threads.
boolean allowsCoreThreadTimeOut() Checks if core threads are allowed to time out.
void allowCoreThreadTimeOut(boolean value) Enables/disables core thread timeout.

4. Queue and Rejection Handling

Method Description
BlockingQueue<Runnable> getQueue() Returns the queue used for holding tasks.
RejectedExecutionHandler getRejectedExecutionHandler() Gets the current rejection policy.
void setRejectedExecutionHandler(RejectedExecutionHandler handler) Sets a new rejection policy.

5. Monitoring & Statistics

Method Description
long getTaskCount() Approximate total number of tasks scheduled.
long getCompletedTaskCount() Number of tasks that have completed.
boolean prestartCoreThread() Starts a single core thread early (without waiting for a task).
int prestartAllCoreThreads() Starts all core threads early.
void purge() Removes canceled tasks from the work queue.

Program Implementation

//ThreadPoolExecutorDemo.java
import java.util.concurrent.*;
public class ThreadPoolExecutorDemo {
    public static void main(String[] args) {
        // Create a ThreadPoolExecutor with corePoolSize 2, maximumPoolSize 4, and a keepAliveTime of 10 seconds.
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, // corePoolSize
                4, // maximumPoolSize
                10, // keepAliveTime
                TimeUnit.SECONDS, // keepAliveTime unit
                new LinkedBlockingQueue<Runnable>(2) // workQueue with capacity 2
        );

        // Add a RejectedExecutionHandler to handle tasks that cannot be executed
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        for (int i = 0; i < 10; i++) {
            int taskNumber = i;
            executor.execute(() -> {
                System.out.println("Executing task " + taskNumber + " in thread " + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000); // Simulate some work
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        executor.shutdown();
        try {
            if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}

/*

C:\>javac ThreadPoolExecutorDemo.java

C:\>java ThreadPoolExecutorDemo
Executing task 0 in thread pool-1-thread-1
Executing task 1 in thread pool-1-thread-2
Executing task 6 in thread main
Executing task 4 in thread pool-1-thread-3
Executing task 5 in thread pool-1-thread-4
Executing task 2 in thread pool-1-thread-1
Executing task 3 in thread pool-1-thread-3
Executing task 7 in thread pool-1-thread-2
Executing task 8 in thread pool-1-thread-4
Executing task 9 in thread pool-1-thread-4

*/

Explanation of above program,

  1. Initialization: A ThreadPoolExecutor is created with a core pool size of 2, a maximum pool size of 4, and a keep-alive time of 10 seconds. The work queue is a LinkedBlockingQueue with a capacity of 2.
  2. Rejection Handler: The CallerRunsPolicy rejection handler is set, which runs the task in the caller’s thread if the executor is saturated.
  3. Submitting Tasks: Ten tasks are submitted to the executor. Each task prints a message and sleeps for 2 seconds to simulate work.
  4. Shutdown: The shutdown() method is called to initiate an orderly shutdown. The awaitTermination method waits for all tasks to complete or a timeout to occur before shutting down.

The ThreadPoolExecutor class is the most powerful and flexible implementation of the ExecutorService interface in Java. It allows developers to manage threads efficiently by customizing thread creation, task scheduling, execution strategies, and rejection policies.

By tuning its core components—such as core pool size, maximum pool size, keep-alive time, and the task queue—you can balance resource usage and responsiveness based on application requirements. Additionally, features like custom ThreadFactory, rejection handlers, monitoring methods, and graceful shutdown mechanisms make it ideal for building scalable and responsive concurrent applications.

Scroll to Top