ExecutorService auto-close
Use try-with-resources for automatic executor shutdown.
Porównanie kodu
✕ 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ć.
Dlaczego nowoczesne podejście wygrywa
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
Wsparcie JDK
ExecutorService auto-close
Dostępne
Widely available since JDK 19 (Sept 2022)
Jak to działa
Since Java 19, ExecutorService implements AutoCloseable. The close() method calls shutdown() and waits for tasks to complete. No more manual try/finally shutdown patterns.
Powiązana dokumentacja