Java Automatic Resource Management | try-with-resources

Automatic Resource Management or try-with-resources is a new exception handling mechanism that was introduced in Java 7, which automatically closes the resources used within the try-catch block.

In general most of the time memory leaks happens when we forget to close resources. If we follow ARM concept we could avoid memory leaks caused by ‘forgetting resource closing in finally block’.

Resource

A Resource is an object which is required to be closed once we used it. For example, a File, database connection, network connection … etc.

Technically a Resource is an object that implements java.lang.AutoCloseable.

Syntax

Example 01 : close resource in finally block manually – old way

In the above example we are closing FileReader explicitly in finally block. Resources closing may throw exception. We need to write exception handling code on resource closing code. We could avoid all these ‘resource closing code’ with Automatic resource management.

Example 02 : Automatic resource management- new way

In the above example, we reads file data using the try-with-resources statement. But if we observe we are not closing the FileReader because it will be automatically closed. This is called Automatic resource management.

We can define our own Resource objects by implementing the AutoCloseable interface and override close() method which gets invoked automatically at runtime after try-catch block executed.

We can declare multiple resources with semicolon separated in try parenthesis.

By default all resources declared at the try block are implicitly final.

Scroll to Top