Java Programming Tutorials

Java programming tutorials with many code examples!

Java try with resources

Problem:

Java 7 finally has shipped try with resources construct that simplifies very common use case when developer had to open some resource and then close in finally block after usage. try with resources makes it very simple. Learn how!

Solution:

The following example shows the problem with the old, verbose approach and the new one, available since Java 7:

package com.farenda.java;

public class TryWithResources {

    static class CostlyResource implements AutoCloseable {

        public static CostlyResource open() {
            System.out.println("CostlyResource.open()");
            return new CostlyResource();
        }

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

    public static void main(String[] args) {
        tryWithFinally();
        tryWithResources();
    }

    private static void tryWithFinally() {
        CostlyResource resource = null;
        try {
            resource = CostlyResource.open();
            System.out.println("Old way: try with finally");
        } finally {
            // Have to check and call close() manually:
            if (resource != null) {
                resource.close();
            }
        }
    }

    private static void tryWithResources() {
        // CostlyResource.close() will be automatically called
        // at the and of the "try" block
        try (CostlyResource resource = CostlyResource.open()) {
            System.out.println("Java 7 way: Try with resources");
        }
    }
}

In the example I’ve created a sample resource – CostlyResource. It works the same as any other implementations of java.lang.AutoCloseable. As you can see the new version is much sorter and makes code more readable.

Running the code gives the following output:

CostlyResource.open()
Old way: try with finally
CostlyResource.close()
CostlyResource.open()
Java 7 way: Try with resources
CostlyResource.close()

Enjoy the new Java 7 feature! :-)

Share with the World!