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.
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


eight × = 16



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.