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

package com.dineshkrish;
/**
* 
* @author Dinesh Krishnan
*
*/
public class MyResource implements AutoCloseable {
public void doSomething() {
System.out.println("Opening the Resource...");
System.out.println("The task has been initiated...");
try {
// Just Delaying the Process
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("The task is completed...");
}
@Override
public void close() throws Exception {
// This will be called automatically
System.out.println("Closing the Resource");
}
}

Application.java

package com.dineshkrish;
public class Application {
public static void main(String[] args) {
// Creating the resource
try(MyResource resource = new MyResource()) {
// Doing some activity
resource.doSomething();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}	
}
}

Output

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

References

1. Oracle Java Documentation

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *