Concurrency Początkujący

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
Widzisz problem z tym kodem? Daj nam znać.
🧹

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.

Stare podejście
Manual Shutdown
Nowoczesne podejście
try-with-resources
Od JDK
19
Poziom trudności
Początkujący
ExecutorService auto-close
Dostępne

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.

Udostępnij 𝕏 🦋 in