java
multithreading
concurrency
executorservice
performance

Executors.newCachedThreadPool versus Executors.newFixedThreadPool

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In Java, the java.util.concurrent package provides a key class called Executors to create and manage thread pools. This functionality is critical for managing concurrent execution of tasks in modern applications. Two of the most commonly used thread pool implementations provided by the Executors class are Executors.newCachedThreadPool() and Executors.newFixedThreadPool(int nThreads). Each has its own characteristics, advantages, and suitable use cases.

Understanding Thread Pools

Before diving into the specifics of these two thread pool types, it's important to understand what a thread pool is. A thread pool manages a group of reusable threads for executing tasks. It allows for efficient execution of concurrent tasks by reducing the overhead of thread creation and destruction.

newCachedThreadPool

The newCachedThreadPool method creates a thread pool that dynamically adjusts the number of threads based on the demand of incoming tasks. It is suitable for applications that require a large but transient number of threads.

Characteristics of newCachedThreadPool

  • Thread Management: It can create new threads as needed but will reuse previously constructed threads when they are available.
  • Idle Timeout: If a thread remains idle for 60 seconds, it gets terminated and removed from the pool. This helps to prevent resource wastage.
  • No Maximum Limit: There is no fixed size for the pool. The number of threads can potentially grow indefinitely based on the application demand.

Example Usage

java
1ExecutorService executor = Executors.newCachedThreadPool();
2
3for (int i = 0; i < 10; i++) {
4    executor.execute(() -> {
5        System.out.println("Task executed by " + Thread.currentThread().getName());
6    });
7}
8
9executor.shutdown();

This example illustrates how a newCachedThreadPool can handle ten tasks. Threads are created and reused dynamically.

Best Use Cases

  • Variable Load: Suitable in scenarios where task load varies significantly.
  • Short-lived, Asynchronous Tasks: Best for executing many short-lived tasks concurrently.

newFixedThreadPool

The newFixedThreadPool method creates a thread pool with a fixed number of threads. It is ideal for applications where predictable and stable thread usage is required.

Characteristics of newFixedThreadPool

  • Fixed Size: You specify the number of threads explicitly during creation.
  • Thread Reuse: Once created, a thread stays in the pool unless explicitly shut down.
  • Task Queueing: Surplus tasks are queued if all threads are active.

Example Usage

java
1ExecutorService executor = Executors.newFixedThreadPool(3);
2
3for (int i = 0; i < 10; i++) {
4    executor.execute(() -> {
5        System.out.println("Task executed by " + Thread.currentThread().getName());
6    });
7}
8
9executor.shutdown();

In this example, up to three tasks can execute simultaneously, while the remaining are queued for execution.

Best Use Cases

  • Steady Task Load: Suitable for scenarios with a consistent task rate.
  • Controlled Resource Usage: Ideal when resource constraints require a limit on concurrent threads.

Key Differences

Below is a comparison of the key characteristics of newCachedThreadPool and newFixedThreadPool.

FeaturenewCachedThreadPoolnewFixedThreadPool
Thread Pool SizeFlexible (Grows as needed)Fixed (Defined by user)
Thread CreationOn-demand (Creates threads as needed)Predefined (Uses initial pool size)
Idle Thread HandlingTerminates after 60 seconds of inactivityRemains until explicitly shutdown
Best Use CasesShort-lived tasks, Variable load tasksSteady load, Controlled resource usage

Conclusion

Choosing the right type of thread pool is crucial for application performance and resource management. newCachedThreadPool is suited for applications with volatile task load, while newFixedThreadPool is optimal for consistent workloads where maintaining a fixed number of threads is practical. Understanding these pool types helps in designing more efficient, responsive, and adaptive concurrent applications in Java.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.