Java - Closing Resources Automatically with AutoClosable

Ömer Kurular
2 min readFeb 23, 2022
Photo by Nagniné on Unsplash

In this article, we are going to cover an important interface that Java 7 brings to stage.

There is a special syntax that Java 7 brought which helps us eleminate finally block used after opening a resource inside try block. Finally block helps us clear resources or do any last operation after leaving try block no matter an exception is thrown or not in try block.

try {
// do operations like reading file
} catch (FileNotFoundException e) {
// do backup operations or log error
} finally {
// do cleanup operations
}

With the feature that comes with Java 7, we can use try-with-resources syntax and let java run our close logic without finally block as follows.

try (InputStream inputStream = new FileInputStream("text.txt")) {
// do something with the input stream
} catch (IOException e) {
e.printStackTrace();
}

As InputStream already implements a Closeable interface (which extends AutoClosable), we can use it with try-with-resources and let java operate close logic of input stream without finally block.

Now, let’s create our own AutoClosable class.

For example, we want to create a connection for a short living task. After that task, we should close the connection so that it does not bother network and resources. To use our connection instance with try with resources, we will implement AutoClosable interface as follows.

public class Connection implements AutoCloseable {

public Connection() {
System.out.println("Connection created");
}

public void connect() throws UnknownHostException {
System.out.println("Connected");
}

public void disconnect() {
System.out.println("Disconnected");
}

@Override
public void close() {
disconnect();
}
}

As you see, after making Connection implement AutoClosable, we need to implement close method where we close the connection. When we use Connection instance with try-with-resources, it will automatically close the connection without needing finally block.

try (Connection connection = new Connection()) {
connection.connect();
// do something with connection
} catch (UnknownHostException e) {
e.printStackTrace();
}

I hope you find the article useful. See you in the next articles.

--

--

Ömer Kurular

I am Ömer and currently working as a full-time software engineer. I will share my knowledge with you I gained through years of professional and self working.