Getty Images/iStockphoto

A simple 'try with resources' in Java example

Java's 'try-with-resources' exception handling feature can help you write better, more effective Java code. Here's a quick example of the try with resources construct in action.

Oracle added the try with resources construct to the Java language in 2011 to help guarantee objects such as network sockets, database connections and references to files and folders are cleanly terminated after their use. Failure to close these resources after a developer opens a handle to them can cause memory leaks, trigger avoidable garbage collection routines and strain a server's CPU.

As you will see in this try with resources example, Java's automatic resource handling feature enables the JVM to automatically invoke the resource termination routines a developer writes inside an AutoCloseable class' close() method. This helps developers write more effective and bug-free code.

How to use Java's try-with-resources statement

To use Java's try-with-resources language feature, the following rules apply:

  • All objects managed by a try with resources statement must implement the AutoCloseable interface.
  • Multiple AutoCloseable objects can be created within Java's try with resources block.
  • Objects declared in a try with resources statement have scope within the try block, but not the catch and finally blocks.
  • The close() method of objects declared in a try with resources block is invoked regardless of whether an exception is thrown during execution.
  • If an exception is thrown in the close() method, it may get categorized as a suppressed exception.

The AutoCloseable interface

AutoCloseable is a functional interface that defines only one method: close(). Here's a simple example of an AutoCloseable class named Door:

class Door implements AutoCloseable {
public void swing() {
System.out.print("The door is swinging. ");
}

public void close() {
System.out.print("Now the door is closed. "); }
}

Try-with-resources example

The following code uses the AutoCloseable Door class in a try with resources statement:

public class TryWithResourcesExample {
public static void main(String[] args) throws Exception {

try (Door door = new Door()) {
door.swing();
} catch (Exception e) { /* do something */ }
} finally { /* do something */ }

}
}

When this try with resources example runs, the output of this code is:

Now the door is swinging. Now the door is closed.

In the code above, here are the steps that make this happen:

  • The developer creates and initializes the Door instance in the try with resources block.
  • The developer explicitly invokes the swing() method.
  • The JVM implicitly calls the close() method after the try block completes.

The close() method is always invoked, regardless of whether a checked or unchecked exception is thrown in one of the try, catch or finally blocks. This simplifies resource management code and makes the application more effective.

The resource referenced by the AutoCloseable object will always be closed if a try with resources statement is used, and potential memory leaks commonly caused by a misallocation of resources are eliminated.

Dig Deeper on JSRs and APIs

SearchAppArchitecture
SearchSoftwareQuality
SearchCloudComputing
SearchSecurity
SearchAWS
Close