Custom AutoClosable in Java

Please go through try-with-resource article on understanding try with resource in java 7

We know that any resource which implements AutoCloseable interface can become a potential candidate for try with resource

Try with resource feature can be used even for custom java class

All we need to do to achieve this is , implement AutoCloseable interface for custom class

AutoCloseable interface contains only one method called close() method

  1. public interface AutoCloseable {
  2.     public void close() throws Exception;
  3. }
public interface AutoCloseable {
    public void close() throws Exception;
}


Any java class that we create can implement this AutoCloseable interface and it can be used with try-resource.

Example :

  1. package com.kb.Exception;
  2.  
  3. public class CustomClass implements AutoCloseable {
  4.    
  5.     public void ExecuteAction() {
  6.         System.out.println("CustomClass executing its action !!");
  7.     }
  8.  
  9.     @Override
  10.     public void close() throws Exception {
  11.         System.out.println("CustomClass closed!!");
  12.        
  13.     }
  14.  
  15. }
package com.kb.Exception;

public class CustomClass implements AutoCloseable {
	
	public void ExecuteAction() {
        System.out.println("CustomClass executing its action !!");
    }

	@Override
	public void close() throws Exception {
		System.out.println("CustomClass closed!!");
		
	}

}


In the above example, we have written custom class which implements AutoCloseable interface

We have also written executeAction() method just to demonstrate that we can have any other methods in our custom class

Now we can use our custom class inside try-resource as below

  1.     public static void main(String[] args) throws Exception {
  2.         try(CustomClass customClass = new CustomClass()){
  3.             customClass.ExecuteAction();
  4.         }
  5.     }
	public static void main(String[] args) throws Exception {
		try(CustomClass customClass = new CustomClass()){
			customClass.ExecuteAction();
	    }
	}



We can see that, at the end close() method is called automatically by Java for our custom class as well

This is because our custom class is also implementing AutoCloseable interface

Note :
Try with resource is best to use as it takes care of closing resources no matter whether resource is a java’s built-in class or custom class

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on