Dot Net For All

C# IDisposeable equivalent in Java

Hello friends, this article will help to understand the C#’s IDisposeable interface equivalent in Java. If you want to work on Java or want to learn it from C# point of view, this article can be helpful.

Why do we use IDisposeable

If we have any resource intensive class or component in our class, we use dispose method to close the resource. Some of the example of such type of resource is File, SQL Connection object. These resources are not managed by .NET runtime and if not closed properly can cause memory leak.

If out class uses any of these resources or resources not managed by .NET framework we can close them in the dispose method.

IDisposable is a contract in the class which enables us to close. This interface has one method named Dispose.

Rule of thumb is that if any class has Dispose and Close method, we should use that method whenever we are done with the usage of that class.

IDisposeable equivalent in Java

If you are reading this article that you are most probably aware about IDisposeable and its utilization.

But we need to look for its equivalent in Java.

AutoCloseable interface is the Java equivalent of IDisposeable in C#.

The way we implement it is the same.

Below is a simple code example to implement the AutoCloseable for a class which is using a resource hungry class. In this case I have used the FileReader class. The deallocation of memory for these classes is not taken care by JVM.

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile implements AutoCloseable {
	FileReader file;
	
	public ReadFile(String fileName) throws IOException {
		file = new FileReader(fileName);		
	}
	
	@Override
	public void close() throws Exception {		
		file.close();
	}

}

I will discuss in the next article how to use the classes which implement AutoCloseable in Java.

In C# we use the using keyword. We will check the using keyword’s equivalent in Java.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview