ExecutorService AutoCloseable Graceful Close

Try-with-resources manages executor shutdown: ExecutorService.close blocks until every submitted task finishes, replacing the manual shutdown sequence.

JavaResilience

Code

snippet
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorAutoClose {

    public static void main(String[] args) throws InterruptedException {
        Instant start = Instant.now();

        // JDK 19+:ExecutorService 实现 AutoCloseable
        // 离开 try 块时 close() 先 shutdown 再阻塞,等所有已提交任务跑完
        try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
            for (int i = 1; i <= 3; i++) {
                int job = i;
                executor.submit(() -> {
                    Thread.sleep(50);
                    return "job " + job + " done";
                });
            }
            System.out.println("submitted; close() will wait for all three");
        }

        Duration waited = Duration.between(start, Instant.now());
        System.out.println("close waited: " + waited.toMillis() + "ms");
    }
}

Inside the snippet

ExecutorService AutoCloseable Graceful Close comes down to the class ExecutorAutoClose.

Repetition is confined to for (int i = 1; i <= 3; i++) — the rest of the file is straight-line. try-with-resources closes each declared resource automatically on every exit path.

Putting it to use

Running the file prints labeled results such as submitted; close() will wait for all three, close waited: — each operation’s effect is visible in the output.

Core lines

try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
for (int i = 1; i <= 3; i++) {
int job = i;
executor.submit(() -> {
Thread.sleep(50);
return "job " + job + " done";
});
}
System.out.println("submitted; close() will wait for all three");
}

Interactive Tools for This Topic

FAQ

What does ExecutorService AutoCloseable Graceful Close print when run?
Execute the whole file; each printed line is prefixed with a label like `submitted; close() will wait for all three`, `close waited:`.