0Pricing
Java Academy · Lesson

ExecutorService and Thread Pool Types

Create fixed, cached, single, and scheduled thread pools and understand when to use each.

Why Use Thread Pools?

Creating a new Thread for every task is expensive — thread creation and destruction has overhead. A thread pool reuses a fixed set of threads to execute many tasks, reducing overhead and controlling resource consumption.

import java.util.concurrent.*;

// Bad practice: new thread per task
new Thread(() -> System.out.println("task")).start();

// Better: reuse threads from a pool
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("task from pool"));
pool.shutdown();

newFixedThreadPool

Creates a pool with exactly N threads. Extra tasks queue up until a thread becomes available. Good when you know the desired parallelism level.

ExecutorService pool = Executors.newFixedThreadPool(4);

for (int i = 0; i < 10; i++) {
    final int taskId = i;
    pool.submit(() -> {
        System.out.println("Task " + taskId + " on " + Thread.currentThread().getName());
    });
}

pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);

All lessons in this course

  1. ExecutorService and Thread Pool Types
  2. Submitting Tasks: Runnable vs Callable
  3. Future and Error Handling
  4. ScheduledExecutorService for Recurring Tasks
← Back to Java Academy