Tuesday, 12 July 2022

Closeable vs AutoCloseable in Java


a.   Closeable interface is introduced in Java 1.5, where as AutoCloseable interface is introduced in Java 1.7.

 

b.   Closeable interface extends AutoCloseable interface.

 

AutoCloseable.java

public interface AutoCloseable {

    void close() throws Exception;

}

 

Closeable.java

public interface Closeable extends AutoCloseable {

    public void close() throws IOException;

}

 

c.    Closeable.close method is restricted to throw IOException, where as AutoCloseable.close method can throw any Exception.

 

d.   calling this AutoCloseable.close method more than once may have some visible side effect, unlike Closeable.close which is required to have no effect if called more than once.

 


 

Closeable, AutoCloseable and try-with-resources statement

 

What is a resource?

Any object that implements java.lang.AutoCloseable interface is a Resource.

 

When you declare the resources using try with resources statement, then the resources will be closed at the end of try-with-resources statement. Following application confirms the same.

 

ResourcesDemo.java

package com.sample.app;

import java.io.Closeable;
import java.io.IOException;

public class ResourcesDemo {

	private static class MyCloseable implements Closeable {

		@Override
		public void close() throws IOException {
			System.out.println("Closing MyCloseable object");
		}

	}

	private static class MyAutoCloseable implements AutoCloseable {

		@Override
		public void close() throws Exception {
			System.out.println("Closing MyAutoCloseable object");
		}

	}

	public static void main(String[] args) {

		System.out.println("Start Execution........");

		try (MyCloseable myCloseable = new MyCloseable(); 
				MyAutoCloseable myAutoCloseable = new MyAutoCloseable();) {
			// Do some work

		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("End Execution........");

	}

}

 

Output

Start Execution........
Closing MyAutoCloseable object
Closing MyCloseable object
End Execution........

 

   

You may like

Interview Questions

How to call super class method from sub class overriding method?

Can an enum has abstract methods in Java?

Can enum implement an interface in Java?

What happen to the threads when main method complete execution

Why System.out.println() is not throwing NullPointerException on null references?

Why should we restrict direct access to instance properties?

No comments:

Post a Comment