Java ThreadPoolExecutor getActiveCount() Method

The ThreadPoolExecutor class in Java provides the getActiveCount() method to get the approximate number of threads that are actively executing tasks. This guide will cover the usage of the getActiveCount() method, explain how it works, and provide concise examples to demonstrate its functionality in real-world use cases.

Introduction

The getActiveCount() method is used to retrieve an estimate of the number of threads that are currently executing tasks in the ThreadPoolExecutor. This can be useful for monitoring and managing the state of the thread pool, allowing you to gain insights into its current load and performance.

getActiveCount Method Syntax

The syntax for the getActiveCount method is as follows:

public int getActiveCount()
  • The method does not take any parameters.
  • The method returns an integer representing the approximate number of actively executing threads.

Examples

Example 1: Basic Usage of getActiveCount()

In this example, we create a ThreadPoolExecutor, submit multiple tasks, and use the getActiveCount() method to print the number of active threads.

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

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

        // 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());
            });
        }

        // Monitor the number of active threads
        while (!executor.isTerminated()) {
            System.out.println("Active threads: " + executor.getActiveCount());
            try {
                Thread.sleep(500); // Pause for a while before checking again
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

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

Output:

Executing task 1 by pool-1-thread-1
Executing task 2 by pool-1-thread-2
Active threads: 2
Active threads: 2
Active threads: 2
Task 1 completed by pool-1-thread-1
Executing task 3 by pool-1-thread-1
Active threads: 2
Task 2 completed by pool-1-thread-2
Executing task 4 by pool-1-thread-2
Active threads: 2
Active threads: 2
Task 3 completed by pool-1-thread-1
Executing task 5 by pool-1-thread-1
Active threads: 2
Task 4 completed by pool-1-thread-2
Task 5 completed by pool-1-thread-1

Example 2: Dynamic Monitoring of Active Threads

In this example, we dynamically monitor the number of active threads while submitting tasks to the ThreadPoolExecutor.

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

public class DynamicMonitoringExample {
    public static void main(String[] args) {
        // Create a ThreadPoolExecutor with 3 threads
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);

        // 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(1000); // Simulate task execution
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskNumber + " completed by " + Thread.currentThread().getName());
            });
        }

        // Monitor the number of active threads dynamically
        new Thread(() -> {
            while (!executor.isTerminated()) {
                System.out.println("Active threads: " + executor.getActiveCount());
                try {
                    Thread.sleep(300); // Pause for a while before checking again
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 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
Active threads: 3
Active threads: 3
Active threads: 3
Task 1 completed by pool-1-thread-1
Executing task 4 by pool-1-thread-1
Active threads: 3
Task 2 completed by pool-1-thread-2
Executing task 5 by pool-1-thread-2
Active threads: 3
Task 3 completed by pool-1-thread-3
Executing task 6 by pool-1-thread-3
Active threads: 3
Task 4 completed by pool-1-thread-1
Executing task 7 by pool-1-thread-1
Active threads: 3
Task 5 completed by pool-1-thread-2
Executing task 8 by pool-1-thread-2
Active threads: 3
Task 6 completed by pool-1-thread-3
Executing task 9 by pool-1-thread-3
Active threads: 3
Task 7 completed by pool-1-thread-1
Executing task 10 by pool-1-thread-1
Active threads: 3
Task 8 completed by pool-1-thread-2
Task 9 completed by pool-1-thread-3
Task 10 completed by pool-1-thread-1

Example 3: Combining getActiveCount() with Other Monitoring Methods

In this example, we use the getActiveCount() method along with other monitoring methods like getPoolSize() and getQueue().size() to get a comprehensive view of the thread pool's state.

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

public class ComprehensiveMonitoringExample {
    public static void main(String[] args) {
        // Create a ThreadPoolExecutor with 4 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(1500); // Simulate task execution
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskNumber + " completed by " + Thread.currentThread().getName());
            });
        }

        // Monitor the state of the executor
        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());
                try {
                    Thread.sleep(500); // Pause for a while before checking again
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 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
Active threads: 4
Total pool size: 4
Tasks in queue: 0
Active threads: 4
Total pool size: 4
Tasks in queue: 0
Task 1 completed by pool-1-thread-1
Executing task 5 by pool-1-thread-1
Active threads: 4
Total pool size: 4
Tasks in queue: 0
Task 2 completed by pool-1-thread-2
Executing task 6 by pool-1-thread-2
Active threads: 4
Total pool size: 4
Tasks in queue: 0
Task 3 completed by pool-1-thread-3
Executing task 7 by pool-1-thread-3
Active threads: 4
Total pool size: 4
Tasks in queue: 0
Task 4 completed by pool-1-thread-4
Executing task 8 by pool-1-thread-4
Active threads: 4
Total pool size: 4
Tasks in queue: 0
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

Conclusion

The ThreadPoolExecutor.getActiveCount() method in Java is used for monitoring the number of threads actively executing tasks in a thread pool.

By using this method, along with other monitoring methods like getPoolSize() and getQueue().size(), you can gain valuable insights into the state and performance of your thread pool.

Comments