Reading history

Java ExecutorService and Thread Pools

6 min read 0 views

Run tasks on Java thread pools with ExecutorService: submit, Future, invokeAll, correct shutdown, race conditions, AtomicInteger and virtual threads.

Creating a new Thread for every task works for a demo, but a server handling thousands of requests would waste memory and time starting threads. Real Java programs hand tasks to an ExecutorService, which keeps a pool of worker threads and reuses them. This lesson covers submitting tasks, getting results through Future, shutting pools down correctly, keeping shared counters safe, and the new virtual threads of Java 21.

In this lesson you will learn

  • Thread pools and why they beat creating threads by hand
  • submit, Callable and Future.get()
  • invokeAll and handling task failures
  • Correct shutdown with shutdown and awaitTermination
  • Race conditions, AtomicInteger and virtual threads

You should know multithreading basics and lambdas.

How a Thread Pool Works

submit(task)task 9task 10task 11task queuetask 5task 6task 7task 8pool of 4 threadsworker 1: task 1worker 2: task 2worker 3: task 3worker 4: task 4takeFutureresultsNew tasks join the queue. When a worker finishes a task, it takes the next one.

Tasks go into a queue. A fixed number of worker threads take tasks from the queue, run them, and come back for more. The threads are created once and reused, and the pool size limits how much work runs at the same time.

Submitting Tasks and Getting Results

import java.util.*;
import java.util.concurrent.*;

public class Main {
    // Pretend work: count primes below n (slow on purpose)
    static int countPrimes(int n) {
        int count = 0;
        for (int i = 2; i < n; i++) {
            boolean prime = true;
            for (int d = 2; (long) d * d <= i; d++) if (i % d == 0) { prime = false; break; }
            if (prime) count++;
        }
        return count;
    }

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        try {
            // submit returns a Future: a handle to a result that will arrive later
            Future<Integer> f = pool.submit(() -> countPrimes(100_000));
            System.out.println("Task submitted, done yet? " + f.isDone());
            System.out.println("Primes below 100,000: " + f.get());   // waits for the result

            // invokeAll runs many tasks and waits for all of them
            List<Callable<String>> jobs = new ArrayList<>();
            for (int limit : new int[]{10_000, 50_000, 200_000, 400_000}) {
                jobs.add(() -> limit + " -> " + countPrimes(limit) + " primes");
            }
            for (Future<String> result : pool.invokeAll(jobs)) {
                System.out.println(result.get());   // results come back in submission order
            }

            // A task that throws: the exception is wrapped in ExecutionException
            Future<Integer> bad = pool.submit(() -> 10 / (args.length));
            try {
                bad.get();
            } catch (ExecutionException e) {
                System.out.println("Task failed: " + e.getCause());
            }
        } finally {
            pool.shutdown();                                  // no new tasks
            boolean ok = pool.awaitTermination(5, TimeUnit.SECONDS);
            System.out.println("Pool shut down cleanly: " + ok);
        }
    }
}

Output

Task submitted, done yet? false
Primes below 100,000: 9592
10000 -> 1229 primes
50000 -> 5133 primes
200000 -> 17984 primes
400000 -> 33860 primes
Task failed: java.lang.ArithmeticException: / by zero
Pool shut down cleanly: true
  • Executors.newFixedThreadPool(4) creates a pool of 4 workers.
  • submit takes a Callable (a lambda that returns a value) and immediately returns a Future. Right after submitting, the task is usually not done yet.
  • future.get() waits until the result is ready. Call it as late as possible so other work can happen meanwhile.
  • invokeAll submits a list of tasks and waits for all of them. The futures come back in the same order as the tasks, even if they finished in a different order.
  • If a task throws, get() throws an ExecutionException; the real problem is in getCause(). Here, args.length is 0, so the task divides by zero.
  • shutdown() stops accepting new tasks and lets running ones finish; awaitTermination waits for that. Forgetting to shut a pool down can keep the program running forever.

Shared Data and Virtual Threads

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws Exception {
        // 1. A plain int shared by threads loses updates
        int[] unsafe = {0};
        AtomicInteger safe = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(8);
        List<Future<?>> fs = new ArrayList<>();
        for (int t = 0; t < 8; t++) {
            fs.add(pool.submit(() -> {
                for (int i = 0; i < 100_000; i++) {
                    unsafe[0]++;              // read-modify-write, not atomic
                    safe.incrementAndGet();   // atomic
                }
            }));
        }
        for (Future<?> f : fs) f.get();
        System.out.println("Expected      : " + 8 * 100_000);
        System.out.println("AtomicInteger : " + safe.get());
        System.out.println("plain int lost updates? " + (unsafe[0] < 8 * 100_000));

        // 2. Virtual threads (Java 21): cheap enough to start one per task
        long start = System.nanoTime();
        try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<Integer>> waits = new ArrayList<>();
            for (int i = 0; i < 1_000; i++) {
                int id = i;
                waits.add(vt.submit(() -> { Thread.sleep(100); return id; }));  // pretend network call
            }
            long sum = 0;
            for (Future<Integer> w : waits) sum += w.get();
            System.out.println("1,000 sleeping tasks finished, sum of ids = " + sum);
        }   // try-with-resources closes the executor and waits for tasks
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.println("Took under 2 seconds? " + (ms < 2000));
        pool.shutdown();
    }
}

Output

Expected      : 800000
AtomicInteger : 800000
plain int lost updates? true
1,000 sleeping tasks finished, sum of ids = 499500
Took under 2 seconds? true
  • unsafe[0]++ is really three steps: read, add, write. When two threads interleave these steps, one update overwrites the other, so the plain counter almost always ends below 800,000. This is a race condition.
  • AtomicInteger.incrementAndGet() does the whole update as one indivisible step, so it always reaches 800,000.
  • Virtual threads (Java 21) are lightweight threads managed by the JVM. Thousands can wait at once cheaply, so 1,000 tasks that each sleep 100 ms finish in a fraction of a second instead of 100 seconds one after another. They suit tasks that spend most of their time waiting for networks, files or databases.
  • Since Java 19, an ExecutorService is AutoCloseable; try-with-resources shuts it down and waits for its tasks.

Choosing a Pool

ExecutorGood for
newFixedThreadPool(n)CPU-heavy work; n ≈ number of CPU cores
newVirtualThreadPerTaskExecutor()Many tasks that mostly wait (I/O)
newSingleThreadExecutor()Tasks that must run one at a time, in order
newScheduledThreadPool(n)Running tasks after a delay or repeatedly

Runtime.getRuntime().availableProcessors() tells you how many cores the machine has.

Common Mistakes

  1. Never calling shutdown(). Non-daemon pool threads keep the JVM alive.
  2. Calling get() right after each submit, which turns parallel work back into sequential work.
  3. Updating shared variables without synchronization; use atomics, locks or concurrent collections.
  4. Ignoring the exception inside ExecutionException; always look at getCause().

Practice Exercises

Exercise 1. Submit three tasks that return the squares of 3, 4 and 5 to a pool of 2 threads and print the sum of the results.

Show answer
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<Integer>> fs = new ArrayList<>();
for (int n : new int[]{3, 4, 5}) fs.add(pool.submit(() -> n * n));
int sum = 0;
for (Future<Integer> f : fs) sum += f.get();
System.out.println(sum);   // 9 + 16 + 25 = 50
pool.shutdown();

Exercise 2. Why does the pool in the first program use try … finally around its work?

Show answer

So that shutdown() runs even if something throws. Otherwise an exception could leave the worker threads running and stop the program from exiting.

Frequently Asked Questions

What is the difference between Runnable and Callable?

Runnable.run() returns nothing and cannot throw checked exceptions. Callable.call() returns a value and can throw. Use Callable when you need a result.

Should I replace all thread pools with virtual threads?

No. Virtual threads help when tasks wait a lot. For CPU-heavy calculations, a fixed pool sized to the number of cores is still the right tool.

Summary

  • An ExecutorService reuses a pool of threads for many tasks.
  • submit returns a Future; get waits for the result and wraps task errors.
  • Always shut pools down; try-with-resources can do it for you.
  • Use atomics for shared counters; use virtual threads for many waiting tasks.

Next: Java CompletableFuture.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *