Java ThreadPoolExecutor allowCoreThreadTimeOut() Method

The ThreadPoolExecutor class in Java provides the allowCoreThreadTimeOut() method to specify whether core threads should be allowed to time out and terminate if no tasks arrive within the keep-alive time. This guide will cover the usage of the allowCoreThreadTimeOut() method, explain how it works, and provide concise examples to demonstrate its functionality in real-world use cases.

Introduction

The allowCoreThreadTimeOut() method is used to allow or disallow core threads to time out and terminate when no tasks are available within the keep-alive time. By default, core threads are not allowed to time out. Allowing core threads to time out can help reduce resource consumption in scenarios where threads are idle for extended periods.

allowCoreThreadTimeOut Method Syntax

The syntax for the allowCoreThreadTimeOut method is as follows:

public void allowCoreThreadTimeOut(boolean value)
  • The method takes a single parameter value:
    • true to allow core threads to time out.
    • false to disallow core threads from timing out.

Examples

Example 1: Allowing Core Threads to Time Out

In this example, we create a ThreadPoolExecutor and configure it to allow core threads to time out after a specified keep-alive time.

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

public class AllowCoreThreadTimeOutExample {
    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 keep-alive time to 10 seconds
        executor.setKeepAliveTime(10, TimeUnit.SECONDS);

        // Allow core threads to time out
        executor.allowCoreThreadTimeOut(true);

        // Submit a task to the executor
        executor.submit(() -> {
            System.out.println("Task executed by " + Thread.currentThread().getName());
        });

        // Shutdown the executor after a delay to observe core thread time out behavior
        try {
            Thread.sleep(15000); // Wait for 15 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }
}

Output:

Task executed by pool-1-thread-1

After waiting for the specified keep-alive time (10 seconds) without new tasks, the core threads will time out and terminate.

Example 2: Observing Core Thread Time Out Behavior

In this example, we observe the behavior of core threads timing out by submitting tasks with delays in between.

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

public class CoreThreadTimeOutBehaviorExample {
    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 keep-alive time to 5 seconds
        executor.setKeepAliveTime(5, TimeUnit.SECONDS);

        // Allow core threads to time out
        executor.allowCoreThreadTimeOut(true);

        // Submit a task to the executor
        executor.submit(() -> {
            System.out.println("Task 1 executed by " + Thread.currentThread().getName());
        });

        // Wait for 6 seconds before submitting another task
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Submit another task to the executor
        executor.submit(() -> {
            System.out.println("Task 2 executed by " + Thread.currentThread().getName());
        });

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

Output:

Task 1 executed by pool-1-thread-1
Task 2 executed by pool-1-thread-2

In this example, you can observe that after the first task completes and no new tasks arrive within the keep-alive time (5 seconds), the core thread times out and terminates. When the second task is submitted after 6 seconds, a new thread is created to execute it.

Conclusion

The ThreadPoolExecutor.allowCoreThreadTimeOut() method in Java provides a way to specify whether core threads should be allowed to time out and terminate if no tasks arrive within the keep-alive time. This can help reduce resource consumption in scenarios where threads are idle for extended periods.

Comments