Skip to lesson

Executors: common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most executor bugs come from a few habits: a pool that is never shut down, a get() that waits too soon, and a pool type that does not fit the work. Each one has a short, reliable fix, and a small task runner can bring all the fixes together.

Mistake 1: forgetting shutdown, or a new pool per request

A pool that is never shut down keeps its non-daemon threads alive, so the program does not exit after main. The worse version hides inside a method that creates a new pool on every call.

Example 1 · Mistake: a new pool on every call leaks threads

PoolLeakDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class PoolLeakDemo {    static List<Thread> livePoolThreads() {        List<Thread> list = new ArrayList<>();        for (Thread t : Thread.getAllStackTraces().keySet()) {            if (t.getName().startsWith("pool-")) {                list.add(t);            }        }        return list;    }
    // WRONG: a new pool for every receipt, never shut down    static ExecutorService sendReceiptLeaky(int roll) throws Exception {        ExecutorService pool = Executors.newFixedThreadPool(2);        pool.submit(() -> System.out.println("Receipt sent to roll " + roll)).get();        return pool;                       // returned only so this demo can clean up    }
    public static void main(String[] args) throws Exception {        List<ExecutorService> leaked = new ArrayList<>();        for (int roll = 1; roll <= 5; roll++) {            leaked.add(sendReceiptLeaky(roll));        }        System.out.println("Leaky version, pool threads alive: " + livePoolThreads().size());
        for (ExecutorService p : leaked) {            p.shutdown();        }        for (Thread t : livePoolThreads()) {            t.join();        }
        ExecutorService shared = Executors.newFixedThreadPool(2);   // RIGHT: one shared pool        try {            for (int roll = 6; roll <= 10; roll++) {                int r = roll;                shared.submit(() -> r).get();            }            System.out.println("Shared pool, pool threads alive: " + livePoolThreads().size());        } finally {            shared.shutdown();            shared.awaitTermination(5, TimeUnit.SECONDS);        }        for (Thread t : livePoolThreads()) {            t.join();        }        System.out.println("After shutdown: " + livePoolThreads().size());    }}
Output
Receipt sent to roll 1
Receipt sent to roll 2
Receipt sent to roll 3
Receipt sent to roll 4
Receipt sent to roll 5
Leaky version, pool threads alive: 5
Shared pool, pool threads alive: 2
After shutdown: 0

What this code does

  • Each call to sendReceiptLeaky left one idle thread behind, so 5 receipts leaked 5 threads; a server handling thousands of requests would leak thousands. (livePoolThreads finds them by their pool- names.)
  • The shared pool never has more than its 2 threads, however many receipts it sends, and the finally block guarantees it is shut down, leaving no pool threads alive.

For example, Executors.newFixedThreadPool(2) created on every call and never shut down leaves threads behind, a thread leak, until the server runs out of memory or threads.

The fix is to create a pool once, share it, and shut it down once when the program or service stops: in a finally block, with the two-step pattern, or with try-with-resources on Java 21.

Mistake 2: calling get() too early

A loop that calls submit(task).get() waits for each task before submitting the next one. The pool never has more than one task to work on, so a pool of 10 threads behaves like a single thread, only with more code.

Example 2 · Mistake: get() inside the submit loop

GetTooEarlyDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.atomic.AtomicInteger;
public class GetTooEarlyDemo {    static final AtomicInteger running = new AtomicInteger();    static final AtomicInteger maxRunning = new AtomicInteger();
    static Callable<Integer> fetchMarks(int marks) {        return () -> {            int now = running.incrementAndGet();            maxRunning.accumulateAndGet(now, Math::max);    // remember the highest value            Thread.sleep(200);            running.decrementAndGet();            return marks;        };    }
    public static void main(String[] args) throws Exception {        ExecutorService pool = Executors.newFixedThreadPool(3);        int[] marks = {78, 91, 66};
        int total = 0;                                      // WRONG: wait inside the loop        for (int m : marks) {            total += pool.submit(fetchMarks(m)).get();        }        System.out.println("Too early: total " + total + ", at most " + maxRunning.get() + " task(s) at once");
        maxRunning.set(0);        List<Future<Integer>> futures = new ArrayList<>();  // RIGHT: submit all, then get        for (int m : marks) {            futures.add(pool.submit(fetchMarks(m)));        }        total = 0;        for (Future<Integer> f : futures) {            total += f.get();        }        System.out.println("Submit first: total " + total + ", at most " + maxRunning.get() + " task(s) at once");        pool.shutdown();    }}
Output
Too early: total 235, at most 1 task(s) at once
Submit first: total 235, at most 3 task(s) at once

What this code does

  • Both loops get the right total, so a test that only checks the answer passes. But in the first loop each get() blocks before the next submit, so the three-thread pool only ever ran one task at a time: about 600 ms instead of 200 ms.
  • maxRunning records the largest number of tasks running together. Submitting all tasks first lets all three run at once.

The fix is to submit everything first, keep the futures in a list, and then call get() on them in a second loop. invokeAll does the same in one call. Use get(timeout, unit) when one slow task must not hold up the rest.

Mistake 3: wrong pool type for the job

Each pool type fits one shape of work. Most real bugs come from using one outside its shape.

Example 3 · Mistake: a cached pool for a flood of slow tasks

WrongPoolTypeDemo.javaJava
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;
public class WrongPoolTypeDemo {    static void slowApiCall() {        try {            Thread.sleep(200);                 // a slow railway API        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    static int largestPool(ExecutorService pool) throws InterruptedException {        for (int i = 0; i < 200; i++) {            pool.execute(WrongPoolTypeDemo::slowApiCall);        }        pool.shutdown();        pool.awaitTermination(30, TimeUnit.SECONDS);        return ((ThreadPoolExecutor) pool).getLargestPoolSize();    }
    public static void main(String[] args) throws InterruptedException {        System.out.println("Cached pool, threads used: " + largestPool(Executors.newCachedThreadPool()));        System.out.println("Fixed pool, threads used:  " + largestPool(Executors.newFixedThreadPool(20)));    }}
Output
Cached pool, threads used: 200
Fixed pool, threads used:  20

What this code does

  • getLargestPoolSize() is the most threads the pool ever had at once. The cached pool made one thread for each of the 200 slow calls; with 20,000 calls it would try to make 20,000.
  • The fixed pool never went past 20 threads; the other calls waited in its queue. It took longer (10 rounds of 200 ms), which is the price of a limit. For blocking calls on Java 21, virtual threads remove that trade-off.
  • A cached pool for a flood of slow tasks creates one thread per task: hundreds or thousands of threads. Use a fixed or bounded pool.
  • A fixed pool sized to the cores for blocking calls leaves the CPU idle while threads wait. Use more threads for I/O-bound work, or virtual threads on Java 21.
  • A pool with several threads for work that must stay in order, such as ledger entries, mixes up the order. Use a single-thread executor.
  • A single-thread executor for many independent slow calls runs them one by one. Use a bigger pool.

A small task runner that combines the fixes

A task runner is a small class that owns one pool and offers simple methods to run work on it. Writing one is a good test of everything in this module.

Example 4 · A task runner for result publishing

TaskRunnerDemo.javaJava
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
class TaskRunner implements AutoCloseable {    private final ExecutorService pool;
    TaskRunner(int threads) {        pool = Executors.newFixedThreadPool(threads);          // created once    }
    List<String> runAll(Map<String, Callable<String>> tasks, long timeoutMs) throws InterruptedException {        Map<String, Future<String>> futures = new LinkedHashMap<>();        for (Map.Entry<String, Callable<String>> e : tasks.entrySet()) {            futures.put(e.getKey(), pool.submit(e.getValue()));   // submit everything first        }        List<String> report = new ArrayList<>();        long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs);        for (Map.Entry<String, Future<String>> e : futures.entrySet()) {            try {                long left = Math.max(0, deadline - System.nanoTime());                report.add(e.getKey() + ": " + e.getValue().get(left, TimeUnit.NANOSECONDS));            } catch (ExecutionException ex) {                report.add(e.getKey() + ": FAILED (" + ex.getCause().getMessage() + ")");            } catch (TimeoutException ex) {                e.getValue().cancel(true);                report.add(e.getKey() + ": TIMED OUT");            }        }        return report;    }
    @Override    public void close() {                                         // two-step shutdown        pool.shutdown();        try {            if (!pool.awaitTermination(1, TimeUnit.SECONDS)) {                pool.shutdownNow();                pool.awaitTermination(1, TimeUnit.SECONDS);            }        } catch (InterruptedException e) {            pool.shutdownNow();            Thread.currentThread().interrupt();        }    }}
public class TaskRunnerDemo {    static Callable<String> publish(String what, int ms, boolean ok) {        return () -> {            Thread.sleep(ms);            if (!ok) {                throw new IllegalStateException("SMS gateway down");            }            return what + " published";        };    }
    public static void main(String[] args) throws InterruptedException {        Map<String, Callable<String>> jobs = new LinkedHashMap<>();        jobs.put("Website", publish("Results page", 50, true));        jobs.put("SMS", publish("SMS alerts", 20, false));        jobs.put("PDF", publish("Marksheet PDFs", 5000, true));        jobs.put("Email", publish("Result emails", 80, true));
        try (TaskRunner runner = new TaskRunner(4)) {            runner.runAll(jobs, 600).forEach(System.out::println);        }        System.out.println("Runner closed");    }}
Output
Website: Results page published
SMS: FAILED (SMS gateway down)
PDF: TIMED OUT
Email: Result emails published
Runner closed

What this code does

  • runAll submits every job before waiting, gives the whole batch one 600 ms deadline, and turns each outcome into a report line: a result, a failure with its real cause, or a timeout (and cancel(true) for the stuck PDF job).
  • TaskRunner owns a single pool and implements AutoCloseable with the two-step shutdown, so try-with-resources closes it on Java 17 as well. Its close() handles InterruptedException itself, as the AutoCloseable documentation advises. The LinkedHashMap keeps the report in the order the jobs were added.

It creates the pool once, submits a whole batch before waiting, reads every result with a timeout, reports failures instead of hiding them, and shuts down cleanly.

Making it AutoCloseable means callers can use it in try-with-resources on any Java version, because the close() is your own method.

Finish up

Mark complete & continue

Next: Normal collections under many threads