JAVA: Automatic Resource Management (ARM)

Overview

  • The try-with-resources statement is a try statement that declares one or more resources.
  • A resource is an object that must be closed after the program is finished with it.
  • The try-with-resources statement ensures that each resource is closed at the end of the statement.
  • Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable,  can be used as a resource.
  • try-with-resources, can have catch and finally. They work as usual and no change in it.
  • ARM returns the  Suppressed Exception details  thrown by close() statement without any add. coding

Sample Code

 
DirtyResource.java :
public class DirtyResource implements AutoCloseable
{
 /*
 *    Need to call this method if you want to access this resource
 *    @throws RuntimeException no matter how you call this method
 */
    public void accessResource()
    {
        throw new RuntimeException("I wanted to access this resource. Bad luck. Its dirty resource !!!");
    }
 
 /*
 *    The overridden closure method from AutoCloseable interface
 *    @throws Exception which is thrown during closure of this dirty resource
 */
    @Override
    public void close() throws Exception
    {
        throw new NullPointerException("Remember me. I am your worst nightmare !! I am Null pointer exception !!");
    }
}

SuppressedExceptionDemoWithTryWithResource.java
public class SuppressedExceptionDemoWithTryWithResource
{
 /*
 *     Demonstrating suppressed exceptions using try-with-resources
 */
   public static void main(String[] arguments) throws Exception
   {
      try (DirtyResource resource= new DirtyResource())
      {
          resource.accessResource();
      } catch ( Exception e1 ) 
    {
       throw e1;
    }
   }
}

Exception printout

[oracle@wls1 ARM]$ java SuppressedExceptionDemoWithTryWithResource
Exception in thread "main" java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!!
    at DirtyResource.accessResource(DirtyResource.java:9)
    at SuppressedExceptionDemoWithTryWithResource.main(SuppressedExceptionDemoWithTryWithResource.java:10)
    Suppressed: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !!
        at DirtyResource.close(DirtyResource.java:19)
        at SuppressedExceptionDemoWithTryWithResource.main(SuppressedExceptionDemoWithTryWithResource.java:11

  • Here we can easily indentify tha we are failing in ARM close() in DirtyResource.close

Reference

Leave a Reply

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