Java ThreadPoolExecutor setCorePoolSize() Method

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

Introduction

The setCorePoolSize() method is used to set the core number of threads that should be maintained in the pool. The core threads are the minimum number of threads that the executor will keep alive, even if they are idle. This method allows you to adjust the pool size dynamically based on your application's requirements.

setCorePoolSize Method Syntax

The syntax for the setCorePoolSize method is as follows:

public void setCorePoolSize(int corePoolSize)
  • The method takes a single parameter:
    • corePoolSize - the new core pool size.

Examples

Example 1: Basic Usage of setCorePoolSize()

In this example, we create a ThreadPoolExecutor, set the core pool size, and submit tasks to the executor.

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

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

        // Set the core pool size to 3
        executor.setCorePoolSize(3);
        System.out.println("Core pool size: " + executor.getCorePoolSize());

        // 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(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:

Core pool size: 3
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-1
Executing task 5 by pool-1-thread-2
Executing task 6 by pool-1-thread-3
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-1
Task 5 completed by pool-1-thread-2
Task 6 completed by pool-1-thread-3

Example 2: Dynamically Adjusting Core Pool Size

In this example, we dynamically adjust the core pool size based on the load of the application.

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

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

        // Submit initial tasks to the executor
        for (int i = 0; i < 4; 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 core pool size
        System.out.println("Initial core pool size: " + executor.getCorePoolSize());

        // Dynamically adjust the core pool size
        executor.setCorePoolSize(3);
        System.out.println("Adjusted core pool size: " + executor.getCorePoolSize());

        // Submit additional tasks to the executor
        for (int i = 4; i < 8; 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:

Executing task 1 by pool-1-thread-1
Executing task 2 by pool-1-thread-2
Executing task 3 by pool-1-thread-1
Executing task 4 by pool-1-thread-2
Initial core pool size: 2
Adjusted core pool size: 3
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-1
Task 1 completed by pool-1-thread-1
Task 2 completed by pool-1-thread-2
Task 3 completed by pool-1-thread-1
Task 4 completed by pool-1-thread-2
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-1

Example 3: Handling Low Load by Reducing Core Pool Size

In this example, we reduce the core pool size when the load is low to save resources.

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

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

        // Submit tasks to the executor
        for (int i = 0; i < 8; 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());
            });
        }

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

        // Wait for some tasks to complete
        try {
            Thread.sleep(3000); // Pause for a while before reducing the core pool size
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Reduce the core pool size
        executor.setCorePoolSize(2);
        System.out.println("Reduced core pool size: " + executor.getCorePoolSize());

        // Submit additional tasks to the executor
        for (int i = 8; i < 10; 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:

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
Initial core pool size: 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
Reduced core pool size: 2
Executing task 9 by pool-1-thread-1
Executing task 10 by pool-1-thread-2
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

Conclusion

The ThreadPoolExecutor.setCorePoolSize() method in Java is used for setting the core number of threads in the pool. By using this method, you can dynamically adjust the core pool size based on the application's load, ensuring efficient resource utilization.

Comments