0

Java – Using ExecutorService, AutoCloseable, and Try-With-Resources

This post demonstrates how to use try-with-resources with ExecutorService.

Requirements

Stuff used in this post.

  • Java 7 or later (JDK)
  • Eclipse Mars

Using The Traditional try-catch-finally

Prior to Java 7, this is how it could be done.

Using Try-with-resources

With Java 7 or later, we can create similar functionality with less codes. First, we need to wrap our ExecutorService in a class that implements AutoCloseable.

Then our main class:

This generates the same output as the original codes.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert