Missing timeout check on ExecutorService.awaitTermination Info

If a timeout check on awaitTermination is missing, a subsequent shutdown operation might forcefully terminate an executing thread. This can make your code harder to debug.

Detector ID
java/missing-timeout-check-on-awaittermination@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1public void shutdownNonCompliant(ExecutorService executor) {
2    executor.shutdown();
3    try {
4        // Noncompliant: awaitTermination might silently time out before all threads finish their execution.
5        executor.awaitTermination(10, TimeUnit.SECONDS);
6    } catch (InterruptedException e) {
7        log.warn("Failed to wait for all tasks to finish", e);
8    }
9}

Compliant example

1public void shutdownCompliant(ExecutorService executor) {
2    executor.shutdown();
3    try {
4        // Compliant: code handles the case when awaitTermination times out.
5        if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
6            log.warn("Failed to terminate executor");
7        }
8    } catch (InterruptedException e) {
9        log.warn("Failed to wait for all tasks to finish", e);
10    }
11}