Concurrency beginner

ExecutorService auto-close

Use try-with-resources for automatic executor shutdown.

✕ Java 8
ExecutorService exec =
    Executors.newCachedThreadPool();
try {
    exec.submit(task);
} finally {
    exec.shutdown();
    exec.awaitTermination(
        1, TimeUnit.MINUTES);
}
✓ Java 19+
try (var exec =
        Executors.newCachedThreadPool()) {
    exec.submit(task);
}
// auto shutdown + await on close
🧹

Auto cleanup

Shutdown happens automatically when the block exits.

🛡️

No leaks

Executor always shuts down, even if exceptions occur.

📖

Familiar pattern

Same try-with-resources used for files, connections, etc.

Old Approach
Manual Shutdown
Modern Approach
try-with-resources
Since JDK
19
Difficulty
beginner
ExecutorService auto-close
Available

Widely available since JDK 19 (Sept 2022)

Since Java 19, ExecutorService implements AutoCloseable. The close() method calls shutdown() and waits for tasks to complete. No more manual try/finally shutdown patterns.

Share 𝕏 🦋 in