Java

ExecutorService, AutoCloseable, and Try-With-Resources In Java

This post demonstrates how to use Java ExecutorService and AutoCloseable with try-with-resources. With ExecutorService, we need to call the shutdown method all the time. However, call the shutdown method means we are writing more codes than we should. There has to be a way to run implicitly! We can do so by wrapping our codes with a class that implements the  AutoCloseable interface. Does it sound interesting? Read on.

Requirements

We used the following stuff for this post.

  • Java 7 or later (JDK)
  • Eclipse Mars
  • Intellij IDEA

Before Java 7 And Without try-with-resource

Before Java 7, we could write our codes with try-catch statements, as shown below. Notice that the codes are verbose for their purpose – we call the shutdown method in the finally clause after checking for null.

Using ExecutorService With try-with-resources And AutoCloseable

With Java 7 and later, we can create similar functionality with fewer codes. First, we need to wrap our ExecutorService in a class that implements the AutoCloseable interface. Then, we use the class in the try-cath-with-resources passing an instance on an ExecutorService.

Therefore in our main class, we write something as shown below. We no longer need the finally clause and explicitly run the shutdown method.

When we run our codes, we get the following output, which is similar to the previous codes’ result, which doesn’t use Java 7.

Why did we need to implement the AutoCloseable interface? Well, any object we use with try-with-resources must implement the AutoCloseable interface, and it always calls the AutoCloseable.close method. Since the ExecutorService class does not implement the AutoCloseable interface, we need to wrap it with something that does. Then, we call the ExecutorService.shutdown method within the close method from the AutoCloseable interface. If we don’t implement the AutoCloseable interface, we’ll get compile-time errors.

And that’s how we can use Java ExecutorService and AutoCloseable with try-with-resources.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like