Course contentsShow
← Java
Lesson 2723 of 2,87050. Executor FrameworkFree lesson

newCachedThreadPool: Elastic Thread Pool for Short Tasks

How newCachedThreadPool creates threads on demand, reuses idle threads for 60 seconds, and scales to zero when idle.

newCachedThreadPool: Elastic Thread Pool for Short Tasks

What you'll learn: How newCachedThreadPool dynamically grows and shrinks to handle unpredictable workloads with short-lived tasks.

The Elastic Thread Pool

Unlike newFixedThreadPool which maintains a constant number of threads, Executors.newCachedThreadPool() creates a dynamic thread pool that expands and contracts based on demand. Think of it like a restaurant that hires temporary staff during rush hour and sends them home when it's quiet.

How It Works

When you submit a task to a cached thread pool:

  1. Reuse first: If an idle thread is available, it executes the task immediately
  2. Create on demand: If all threads are busy, a new thread is created to handle the task
  3. 60-second timeout: Idle threads wait 60 seconds for new work before terminating
  4. Scales to zero: When no tasks arrive, the pool eventually shrinks to zero threads
ExecutorService executor = Executors.newCachedThreadPool();

// Submit 100 short tasks
for (int i = 0; i < 100; i++) {
    executor.execute(() -> {
        System.out.println("Quick task on " + Thread.currentThread().getName());
    });
}

executor.shutdown();
// After 60 seconds of inactivity, all threads will terminate

When to Use It

Ideal for:

  • Many short-lived, asynchronous tasks
  • Unpredictable workload spikes
  • Low-latency requirements (no queueing delay)

Avoid for:

  • Long-running tasks (thread explosion risk)
  • Predictable, steady workloads (use newFixedThreadPool instead)
  • Memory-constrained environments (unbounded thread creation)

The pool has no hard limit on threads—if you submit 1,000 concurrent tasks, it creates 1,000 threads!

Key Takeaway: newCachedThreadPool provides elastic scaling with automatic thread recycling after 60 seconds of idleness, perfect for bursty short-task workloads but dangerous with long-running or unlimited concurrent tasks.