Java 9 Try-With-Resources Enhancement

[Last Updated: Oct 22, 2017]

In Java 7 and 8, we can use try-with-resource block which allows to declare closeable resources. Any object that implements java.lang.AutoCloseable can be used in a try-with-resource block. Following is the Java 7/8 syntax of doing that:

 try(InputStream stream1 = new InputStream(....);
     InputStream stream2 = new InputStream(....)){

When the above block terminates, either normally or due to an exception, the close() methods of the each stream objects are automatically called in the order in which they are declared.

Java 9 provides additional flexibility while using try-with-resource blocks, now we don't have the restriction of declaring each closeable object inside try parentheses anymore, we just need to use their references:

 InputStream stream1 = new InputStream(....);
 InputStream stream2 = new InputStream(....);


For simplicity, we are going to use a String object as the InputStream source. We are also going to override close() method to know when it is called.

public class TryWithResourceExample {
  public static void main(String[] args) throws IOException {
      InputStream inputStream = getInputStream();

      try (inputStream) {
          String s = new String(inputStream.readAllBytes());

      System.out.println("after try-with-resource block");

  public static InputStream getInputStream() {
      return new ByteArrayInputStream("test string".getBytes()) {
          public void close() throws IOException {


test string
after try-with-resource block

Example Project

Dependencies and Technologies Used:

  • JDK 9.0.1
Java 9 Try-With-Resource Examples Select All Download
  • java9-try-with-resource-example
    • src
      • com
        • logicbig
          • example

    See Also