What is the difference between fixed thread pool and cached thread pool?

A Fixed Thread Pool and a Cached Thread Pool are both implementations provided by ExecutorService, but they differ in how they create and manage threads. A Fixed Thread Pool maintains a predefined number of threads throughout its lifetime, whereas a Cached Thread Pool dynamically creates new threads when needed and reuses idle threads for future tasks.

Key Points: • Fixed Thread Pool limits the number of concurrent threads, helping control CPU and memory usage. • Cached Thread Pool can create an unlimited number of threads, making it suitable for many short-lived asynchronous tasks. • Fixed pools provide predictable performance, while cached pools prioritize responsiveness and scalability.

Example: Consider a banking application that processes transactions. A Fixed Thread Pool can be used to limit the number of simultaneous transaction-processing threads and prevent resource exhaustion. In contrast, a Cached Thread Pool is useful for handling short-lived requests such as sending notifications or generating temporary reports where the workload varies significantly.

Code Example:

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

public class ThreadPoolExample {

    public static void main(String[] args) {

        ExecutorService fixedPool = Executors.newFixedThreadPool(5);

        ExecutorService cachedPool = Executors.newCachedThreadPool();

fixedPool.submit(() ->

            System.out.println("Task executed by Fixed Thread Pool")
        );

cachedPool.submit(() ->

            System.out.println("Task executed by Cached Thread Pool")
        );

        fixedPool.shutdown();
        cachedPool.shutdown();
    }
}

Interview Tip: A concise interview answer is: A Fixed Thread Pool maintains a fixed number of worker threads and provides better control over system resources, while a Cached Thread Pool creates threads on demand and reuses idle threads, making it suitable for large numbers of short-lived tasks with unpredictable workloads.