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.

Java · intermediate · 6 min · 15 steps · free

What you'll learn

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().

Common mistakes

Best practices

Key takeaways

Check yourself

Which interface must the resource implement?

Answer: AutoCloseable. Closeable also works, as it extends AutoCloseable.

When does close() run?

Answer: When the try block ends, normally or by exception. Always.

·

More in More Language Features