Advanced Java: Collections, Generics and More ยท More Language Features

try-with-resources and AutoCloseable

Open a resource in the try header and Java closes it for you at the end, even if something goes wrong.

TryWithResourcesDemo.java

class Connection implements AutoCloseable {
    String name;
    Connection(String name) {
        this.name = name;
        System.out.println("open " + name);
    }

    String query() {
        return "data from " + name;
    }

    @Override
    public void close() {
        System.out.println("close " + name);
    }
}

public class TryWithResourcesDemo {
    public static void main(String[] args) {
        String result;
        try (Connection db = new Connection("db")) {
            result = db.query();
        }                                         // close() runs automatically here
        System.out.println(result);
    }
}

Step by step

  1. The resource is created in the try header.
  2. Java enters the constructor. Before its own code runs, the parent class's constructor (here Object) runs first.
  3. name in the Connection object changes from null to "db".
  4. It prints open db.
  5. Connection() has finished, so its variables are gone.
  6. db is created on the stack and points to a new Connection on the heap: {name: "db"}.
  7. Use the resource.
  8. query() has finished, so its variables are gone.
  9. Use the resource.
  10. Leaving the try block: Java calls close() automatically.
  11. It prints close db.
  12. close() has finished, so its variables are gone.
  13. db goes out of scope and disappears.
  14. It prints data from db.
  15. open, close, then the result: the connection was closed without us writing close().