Jamie Craane

About Jamie Craane

Jamie develops software professionally since 2001 for a variety of small and large organizations. He watches and studies new technology closely to find out how this can be applied in software solutions. Besides developing software, Jamie gives presentations and training on a regular basis on various subjects and technologies.

Java 7 try-with-resources

Java 7 provides better resource management for resources that need to be closed when finished working with, for example files, streams, database connection and sockets. This language construct is called the try-with-resources statement. The mechanism that makes this work is called the AutoCloseable interface. The Java 7 resource classes all implement this interface. The signature of this interface looks like this:
 
 
 
 
 

public interface AutoCloseable {
    void close() throws Exception;
}

It declares one method, close(), which is automatically invoked on objects managed by the try-with-resources statement.

Although Java 7 resource classes implement this interface, a lot of time the libraries you use do not because the library is not updated to use the AutoCloseable interface or the project cannot simply update to a newer version.

Most of the time this is easy to solve. Just subclass the resource that should be able to participate in the try-with-resources statement. Take the ITextRenderer (form the Flying Saucer project) as an example. When finished working with the ITextRenderer, the finishPDF() method should be called. Normally you would do that in a finally block. By creating a new class extending from ITextRenderer and implementing the AutoCloseable interface this class can participate in automatic resource management. The AutoCloseableITextRenderer looks like this:

public class AutoCloseableITextRenderer extends ITextRenderer implements AutoCloseable {
    @Override
    public void close() {
        super.finishPDF();
    }
}

Extending the original class makes the most sense since the subclass is an ITextRenderer. You would use composition if the class cannot be extended because it is final.

And this is how you would use it:

try (final AutoCloseableITextRenderer iTextRenderer = new AutoCloseableITextRenderer()) {
            ByteArrayOutputStream out; // contains the data to be converted to PDF, not shown here.

            iTextRenderer.setDocumentFromString(new String(out.toByteArray()));
            iTextRenderer.layout();
            iTextRenderer.createPDF(pdfOutputStream);
            pdfOutputStream.flush();
        }

Thats all. Please note that I did not throw an exception from the close() method in the AutoCloseableITextRenderer. The Javadoc of the AutoCloseable interface says the following about this:

While this interface method is declared to throw {@code Exception}, implementers are strongly encouraged to declare concrete implementations of the {@code close} method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.
 

Reference: Java 7 try-with-resources from our JCG partner Jamie Craane at the Jamie Craane’s Blog blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


5 × = fifteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close