Sudden service shutdown might prevent a graceful termination of threads. This can make your code harder to debug.
1void shutdownNonCompliant(ExecutorService executorService) throws InterruptedException {
2 if (executorService != null) {
3 // Noncompliant: shutdownNow is called which suddenly shuts down executorService.
4 executorService.shutdownNow();
5 }
6}
1void shutdownCompliant(ExecutorService executorService) throws InterruptedException {
2 if (executorService != null) {
3 // Compliant: attempts graceful shutdown before doing so forcefully.
4 executorService.shutdown();
5 if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
6 throw new IllegalStateException("Timed out while waiting for executing threads to terminate");
7 }
8 executorService.shutdownNow();
9 }
10}