Skip to main content

Lesson 4 of 8

ExecutorService & Thread Pools

Creating raw threads for every task is expensive and uncontrolled. ExecutorService manages a pool of worker threads - reusing them for many tasks. Thread pools are the right abstraction for concurrent task execution in production Java.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

ExecutorService - Thread Pool Management

ExecutorService - Thread Pool Management
import java.util.concurrent.*;
import java.util.List;

public class ExecutorServiceDemo {
    public static void main(String[] args) throws Exception {

        // Types of thread pools (Executors factory methods)
        ExecutorService fixed    = Executors.newFixedThreadPool(4);    // 4 threads, queue tasks when busy
        ExecutorService cached   = Executors.newCachedThreadPool();    // grows/shrinks; 60s idle timeout
        ExecutorService single   = Executors.newSingleThreadExecutor(); // 1 thread, sequential queue
        ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(2); // cron/delay

        // Submit Runnable (no return value)
        fixed.submit(() -> System.out.println("Task 1 on: " + Thread.currentThread().getName()));

        // Submit Callable (returns a result via Future)
        Future<List<Book>> catalogFuture = fixed.submit(() -> {
            // simulate slow catalog load
            Thread.sleep(100);
            return loadCatalogFromDb();
        });

        // Do other work while catalog loads...
        System.out.println("Main thread doing other work...");

        // Get the result (blocks until done)
        List<Book> catalog;
        try {
            catalog = catalogFuture.get(5, TimeUnit.SECONDS);  // timeout: fail-safe
            System.out.println("Loaded " + catalog.size() + " books");
        } catch (TimeoutException e) {
            System.err.println("Catalog load timed out");
            catalogFuture.cancel(true);  // interrupt the task
        }

        // Submit multiple tasks and wait for all
        List<Callable<String>> tasks = List.of(
            () -> { Thread.sleep(50);  return "Task A"; },
            () -> { Thread.sleep(100); return "Task B"; },
            () -> { Thread.sleep(30);  return "Task C"; }
        );
        List<Future<String>> futures = fixed.invokeAll(tasks);  // waits for ALL
        for (Future<String> f : futures) {
            System.out.println(f.get());
        }

        // Scheduled tasks
        scheduled.schedule(() -> System.out.println("Delayed task"), 2, TimeUnit.SECONDS);
        scheduled.scheduleAtFixedRate(() -> System.out.println("Periodic check"),
            0, 30, TimeUnit.SECONDS);         // every 30 seconds

        // ALWAYS shutdown properly - otherwise JVM won't exit
        fixed.shutdown();
        fixed.awaitTermination(10, TimeUnit.SECONDS);

        // Or force shutdown
        List<Runnable> unfinished = fixed.shutdownNow();  // interrupts running tasks
        scheduled.shutdown();
    }

    static List<Book> loadCatalogFromDb() { return new java.util.ArrayList<>(); }
}

Quick Quiz

Tip

Tip

Practice ExecutorService Thread Pools in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for ExecutorService & Thread Pools

Practice Task

Note

Practice Task - (1) Write a working example of ExecutorService Thread Pools from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with ExecutorService Thread Pools is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done