Java Executors newFixedThreadPool() Method

The Executors class in Java provides the newFixedThreadPool() method to create a thread pool with a fixed number of threads. This guide will cover the usage of the newFixedThreadPool() method, explain how it works, and provide concise examples to demonstrate its functionality in real-world use cases.

Introduction

The Executors.newFixedThreadPool() method creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread becomes available.

newFixedThreadPool Method Syntax

The syntax for the newFixedThreadPool method is as follows:

public static ExecutorService newFixedThreadPool(int nThreads)
  • The method takes a single parameter nThreads, which specifies the number of threads in the pool.
  • The method returns an ExecutorService that can be used to manage asynchronous task execution.

Examples

Example 1: Basic Usage

In this example, we create a fixed thread pool with a specified number of threads and submit multiple tasks to it.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPoolExample {
    public static void main(String[] args) {
        // Create a fixed thread pool with 3 threads
        ExecutorService executor = Executors.newFixedThreadPool(3);

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

Executing task 1 by pool-1-thread-1
Executing task 2 by pool-1-thread-2
Executing task 3 by pool-1-thread-3
Task 1 completed by pool-1-thread-1
Executing task 4 by pool-1-thread-1
Task 2 completed by pool-1-thread-2
Executing task 5 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

Example 2: Handling Multiple Tasks

In this example, we use a fixed thread pool to handle multiple tasks concurrently, demonstrating its capability to manage a fixed number of threads.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultipleTasksExample {
    public static void main(String[] args) {
        // Create a fixed thread pool with 4 threads
        ExecutorService executor = 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("Task " + taskNumber + " started 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:

Task 1 started by pool-1-thread-1
Task 2 started by pool-1-thread-2
Task 3 started by pool-1-thread-3
Task 4 started by pool-1-thread-4
Task 1 completed by pool-1-thread-1
Task 5 started by pool-1-thread-1
Task 2 completed by pool-1-thread-2
Task 6 started by pool-1-thread-2
Task 3 completed by pool-1-thread-3
Task 7 started by pool-1-thread-3
Task 4 completed by pool-1-thread-4
Task 8 started 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

Example 3: Processing a Fixed Number of Threads for a Long-Running Task

In this example, we demonstrate using a fixed thread pool to process a long-running task, ensuring that the pool maintains a fixed number of threads.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LongRunningTaskExample {
    public static void main(String[] args) {
        // Create a fixed thread pool with 2 threads
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // Submit long-running tasks to the executor
        for (int i = 0; i < 4; i++) {
            final int taskNumber = i + 1;
            executor.submit(() -> {
                System.out.println("Long-running task " + taskNumber + " started by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(3000); // Simulate long-running task
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Long-running task " + taskNumber + " completed by " + Thread.currentThread().getName());
            });
        }

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

Output:

Long-running task 1 started by pool-1-thread-1
Long-running task 2 started by pool-1-thread-2
Long-running task 1 completed by pool-1-thread-1
Long-running task 3 started by pool-1-thread-1
Long-running task 2 completed by pool-1-thread-2
Long-running task 4 started by pool-1-thread-2
Long-running task 3 completed by pool-1-thread-1
Long-running task 4 completed by pool-1-thread-2

Conclusion

The Executors.newFixedThreadPool() method in Java is used for creating a thread pool with a fixed number of threads. This thread pool reuses a fixed number of threads to execute tasks, providing a way to limit the number of active threads and manage concurrency efficiently.

Comments