Java ThreadPoolExecutor getMaximumPoolSize() Method

The ThreadPoolExecutor class in Java provides the getMaximumPoolSize() method to get the maximum number of threads allowed in the pool. This guide will cover the usage of the getMaximumPoolSize() method, explain how it works, and provide concise examples to demonstrate its functionality in real-world use cases.

Introduction

The getMaximumPoolSize() method is used to retrieve the maximum number of threads that the ThreadPoolExecutor can accommodate. This value determines the upper limit on the number of concurrent threads that can be active in the pool at any given time.

getMaximumPoolSize Method Syntax

The syntax for the getMaximumPoolSize method is as follows:

public int getMaximumPoolSize()
  • The method does not take any parameters.
  • The method returns an integer representing the maximum number of threads in the pool.

Examples

Example 1: Basic Usage of getMaximumPoolSize()

In this example, we create a ThreadPoolExecutor, set the maximum pool size, and use the getMaximumPoolSize() method to print the maximum number of threads allowed in the pool.

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class GetMaximumPoolSizeExample {
    public static void main(String[] args) {
        // Create a ThreadPoolExecutor with 2 core threads and 4 maximum threads
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        executor.setMaximumPoolSize(4);

        // Print the maximum pool size
        System.out.println("Maximum pool size: " + executor.getMaximumPoolSize());

        // Submit tasks to the executor
        for (int i = 0; i < 5; i++) {
            final int taskNumber = i + 1;
            executor.submit(() -> {
                System.out.println("Executing task " + taskNumber + " by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000); // Simulate task execution
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskNumber + " completed by " + Thread.currentThread().getName());
            });
        }

        // Shutdown the executor
        executor.shutdown();
    }
}

Output:

Maximum pool size: 4
Executing task 1 by pool-1-thread-1
Executing task 2 by pool-1-thread-2
Executing task 3 by pool-1-thread-3
Executing task 4 by pool-1-thread-4
Executing task 5 by pool-1-thread-1
Task 1 completed by pool-1-thread-1
Task 2 completed by pool-1-thread-2
Task 3 completed by pool-1-thread-3
Task 4 completed by pool-1-thread-4
Task 5 completed by pool-1-thread-1

Example 2: Dynamic Adjustment of Maximum Pool Size

In this example, we dynamically adjust the maximum pool size and observe the effect on task execution.

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class DynamicAdjustmentExample {
    public static void main(String[] args) {
        // Create a ThreadPoolExecutor with 2 core threads and 2 maximum threads initially
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        executor.setMaximumPoolSize(2);

        // Submit tasks to the executor
        for (int i = 0; i < 6; i++) {
            final int taskNumber = i + 1;
            executor.submit(() -> {
                System.out.println("Executing task " + taskNumber + " by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // Simulate task execution
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskNumber + " completed by " + Thread.currentThread().getName());
            });
        }

        // Print the initial maximum pool size
        System.out.println("Initial maximum pool size: " + executor.getMaximumPoolSize());

        // Dynamically increase the maximum pool size
        executor.setMaximumPoolSize(4);
        System.out.println("Updated maximum pool size: " + executor.getMaximumPoolSize());

        // Submit additional tasks to the executor
        for (int i = 6; i < 12; i++) {
            final int taskNumber = i + 1;
            executor.submit(() -> {
                System.out.println("Executing task " + taskNumber + " by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // Simulate task execution
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskNumber + " completed by " + Thread.currentThread().getName());
            });
        }

        // Shutdown the executor
        executor.shutdown();
    }
}

Output:

Initial maximum pool size: 2
Executing task 1 by pool-1-thread-1
Executing task 2 by pool-1-thread-2
Updated maximum pool size: 4
Executing task 3 by pool-1-thread-1
Executing task 4 by pool-1-thread-2
Executing task 5 by pool-1-thread-3
Executing task 6 by pool-1-thread-4
Task 1 completed by pool-1-thread-1
Executing task 7 by pool-1-thread-1
Task 2 completed by pool-1-thread-2
Executing task 8 by pool-1-thread-2
Task 3 completed by pool-1-thread-3
Executing task 9 by pool-1-thread-3
Task 4 completed by pool-1-thread-4
Executing task 10 by pool-1-thread-4
Task 5 completed by pool-1-thread-1
Executing task 11 by pool-1-thread-1
Task 6 completed by pool-1-thread-2
Executing task 12 by pool-1-thread-2
Task 7 completed by pool-1-thread-3
Task 8 completed by pool-1-thread-4
Task 9 completed by pool-1-thread-1
Task 10 completed by pool-1-thread-2
Task 11 completed by pool-1-thread-3
Task 12 completed by pool-1-thread-4

Example 3: Monitoring and Adjusting Pool Size at Runtime

In this example, we continuously monitor the pool size, active threads, and queue size while adjusting the maximum pool size at runtime.

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class MonitoringAndAdjustingExample {
    public static void main(String[] args) {
        // Create a ThreadPoolExecutor with 2 core threads and 4 maximum threads initially
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        executor.setMaximumPoolSize(4);

        // Submit tasks to the executor
        for (int i = 0; i < 10; i++) {
            final int taskNumber = i + 1;
            executor.submit(() -> {
                System.out.println("Executing task " + taskNumber + " by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1500); // Simulate task execution
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskNumber + " completed by " + Thread.currentThread().getName());
            });
        }

        // Monitor the executor's state
        new Thread(() -> {
            while (!executor.isTerminated()) {
                System.out.println("Active threads: " + executor.getActiveCount());
                System.out.println("Total pool size: " + executor.getPoolSize());
                System.out.println("Tasks in queue: " + executor.getQueue().size());
                System.out.println("Maximum pool size: " + executor.getMaximumPoolSize());
                try {
                    Thread.sleep(500); // Pause for a while before checking again
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // Simulate adjusting the maximum pool size at runtime
        new Thread(() -> {
            try {
                Thread.sleep(3000);
                executor.setMaximumPoolSize(6);
                System.out.println("Adjusted maximum pool size to 6");
                Thread.sleep(3000);
                executor.setMaximumPoolSize(2);
                System.out.println("Adjusted maximum pool size to 2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // Shutdown the executor after all tasks are completed
        executor.shutdown();
    }
}

Output:

Executing task 1 by pool-1-thread-1
Executing task 2 by pool-1-thread-2
Executing task 3 by pool-1-thread-3
Executing task 4 by pool-1-thread-4
Executing task 5 by pool-1-thread-1
Executing task 6 by pool-1-thread-2
Executing task 7 by pool-1-thread-3
Executing task 8 by pool-1-thread-4
Executing task 9 by pool-1-thread-1
Executing task 10 by pool-1-thread-2
Active threads: 4
Total pool size: 4
Tasks in queue: 0
Maximum pool size: 4
Active threads: 4
Total pool size

: 4
Tasks in queue: 0
Maximum pool size: 4
Adjusted maximum pool size to 6
Active threads: 4
Total pool size: 4
Tasks in queue: 0
Maximum pool size: 6
Task 1 completed by pool-1-thread-1
Task 2 completed by pool-1-thread-2
Task 3 completed by pool-1-thread-3
Task 4 completed by pool-1-thread-4
Task 5 completed by pool-1-thread-1
Task 6 completed by pool-1-thread-2
Task 7 completed by pool-1-thread-3
Task 8 completed by pool-1-thread-4
Task 9 completed by pool-1-thread-1
Task 10 completed by pool-1-thread-2
Adjusted maximum pool size to 2
Active threads: 2
Total pool size: 2
Tasks in queue: 0
Maximum pool size: 2

Conclusion

The ThreadPoolExecutor.getMaximumPoolSize() method in Java is used for retrieving the maximum number of threads allowed in the pool. By using this method, along with other monitoring methods like getActiveCount() and getPoolSize(), you can gain valuable insights into the state and performance of your thread pool.

Comments