Try with Resource Statement using AutoCloseable Example in Java

Try with Resource Statement Example in Java

In this article, I am sharing the example of Try with Resource Statement in Java, Generally During the Software development, Managing the resources such as Database Connections, File System, Socket Connections and etc. It`s one of major responsibility of the developers. Whenever we deals with such resources, We have to be more careful regarding Opening and Closing them properly.

Common Problem

When we take an example of transactions on database, In order to perform transaction on database, first you may have to Open the Database Connection -> Perform the Transaction -> Close the Database Connection. There might be chances the transaction can be succeeded or may not, But both scenario Its developer responsibility to close the Connection Resources. Unfortunately, Many developers may forget to do this during the development.

Solution

Now we got the solution for it. In JDK 1.7 version, The oracle have Introduced concept called Try with Resource Statement in Java. In this post, I have attached simple example about, Try with Resource Statement using AutoCloseable Example in Java.

AutoCloseable Example

The AutoCloseable is a Interface, Its belongs to java.lang package. Which should be implemented on your Custom Resource class and you have to override the abstract method called close(). Which will be called automatically, also You can write closing resource business logic in it.

MyResource.java

Application.java

Output

—————
Opening the Resource…
The task has been initiated…
The task is completed…
Closing the Resource

References

1. Oracle Java Documentation