JavaRush /Java Blog /Random EN /Java 7 try-with-resources
DarthVictor
Level 28

Java 7 try-with-resources

Published in the Random EN group
Beginning with version 7, Java offers improved management of resources that should be closed when finished working with them. Such resources include, for example, files, streams, database connections and sockets. This purpose is served by a special language construct try-with-resources. In order for this automatic closing to work, a special interface has been created AutoCloseable. Java 7 try-with-resources - 1In Java 7, all resource classes implement this interface. Its signature looks like this:
public interface AutoCloseable {
    void close() throws Exception;
}
The interface declares a method close()that is automatically called on the objects served by the construct try-with-resources. Although the resource classes in Java 7 implement this interface, many of the libraries you use do not, either because the library has not yet been updated to work with the AutoCloseable interface or you simply do not have the ability to update the library. In most cases this can be easily resolved. Inherit the resource class that should participate in the try-with-resources. Let's take for example ITextRenderer(from the Flying Saucer project). After finishing working with ITextRenderer, the method should be called finishPDF(). Normally you would do this in a block finally. But when you create a new class that extends ITextRendererand implements the interface AutoCloseable, you can include it in the try-with-resources. The new class AutoCloseableITextRendererwill look like this:
public class AutoCloseableITextRenderer extends ITextRenderer implements AutoCloseable {
    @Override
    public void close() {
        super.finishPDF();
    }
}
Extending the original class in a descendant is the most reasonable solution, since the new class will still be ITextRenderer. In case the original class is declared as final, composition must be used. And this is what usage would look like:
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();
        }
That's all. Please note that I did not throw an exception from a method close()in the AutoCloseableITextRenderer. The Javadoc of the interface AutoCloseablesays the following about this: Although the interface method is declared to throw exceptions Exception, implementers of this method are strongly recommended to use more specific exception classes when implementing the method, or not to throw exceptions at all if the method close()cannot fail.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION