Java 7 gets Automatic Resource Management


Java 7 is adding support for a new try-with-resources code-block construct that allows the runtime environment to automatically manage closeable resources e.g. streams.

It started out as a proposal in Feb 2007 by Joshua Bloch to add try blocks to automatically manage resources will now be available in Java 7.

The update specification for the try-catch block now looks like:

TryStatement:
    try ResourceSpecification Block Catches(opt) Finally(opt)

Supporting new grammar productions are added:

ResourceSpecification:
    ( Resources )
Resources:
    Resource
    Resource ; Resources
Resource:
    VariableModifiers Type VariableDeclaratorId = Expression
    Expression

Here is a simple code example which shows a typical try-catch-finally block, making sure it closes up everything when its done,  being sure to catch the buried exception in finally block that may occur and which is why 2/3rd of the uses of close method usage in JDK itself! are wrong as mentioned by Joshua in his proposal.

private static void customBufferStreamCopy(File source, File target) {
    InputStream fis = null;
    OutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);

        byte[] buf = new byte[8192];

        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    } finally {
        close(fis);
        close(fos);
    }
}

private static void close(Closeable closable) {
    if (closable != null) {
        try {
            closable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

with the new try-with-resource language feature in Java 7, you declare your stream/resource arguments as part of the try-construct, and the compiler generates code that manages those resources automatically and cleanly for you.

Here is the same code with the new syntax:

private static void customBufferStreamCopy(File source, File target) {
    try (InputStream fis = new FileInputStream(source);
        OutputStream fos = new FileOutputStream(target)){

        byte[] buf = new byte[8192];

        int i;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

In order to make use of the new try-with-resources construct in Java 7, your resource must implement the java.lang.AutoCloseable interface and it’s single void close() method.

Checking the Javadoc for AutoCloseable you can see that almost every applicable class in the platform has been modified to include this functionality, so out of the box most all of your streaming/reader/writer work in IO, Net, XML, etc. will support this new use-case.

And above all there aren’t any performance implications for using the new construct as it is a simple syntactic sugar as the compiler will generate the right code for you that will take care of the resource management correctly much like the enhanced for loop.

Advertisements
Java 7 gets Automatic Resource Management

One thought on “Java 7 gets Automatic Resource Management

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s