Using try-with-resources statement in Java 7

August 23, 2020 No comments Java IO try-with-resources Java

1. Introduction

In this article, we will present the try-with-resources statement introduced in Java 7. This special feature ensures that every resource will be closed at the end of the statement. In this tutorial, we will present the old way to deal with closing resources before Java 7, and gives some example that will show the advantage of this modern solution.

2. Cleanup resources the old way

Let's start with the example of closing resources before Java 7.

package com.frontbackend.java.io.trywithresources;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileBeforeJava7 {

    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("/tmp/test.txt"));

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

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

        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

In applications with many IO operations, this kind of code fragment is very common. The problem is we need to add the finally block every time we have to clean up the resources. This is not enough, because often close(...) methods also throw an exception, so we need to add a try-catch statement in this finally block. The code is getting even uglier when we have more than one resource to handle.

3. Using try-with-resources from Java 7

The sample program that reads a file from /tmp/test.txt path using try-with-resources statement will look like the following:

package com.frontbackend.java.io.trywithresources;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileUsingTryWithResources {

    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("/tmp/test.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

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

Here we used try condition with brackets where we put resources that need to be closed BufferedReader.

Java 7 introduced a new interface java.lang.AutoCloseable with a single method close(). Every AutoCloseable resource in try-with-resource block will be closed by calling that method by JVM when the resource is no longer needed, practically right after block ends.

4. Creating custom AutoCloseable object

This sample program will demonstrate how closing resources in try-with-resources statement works:

package com.frontbackend.java.io.trywithresources;

public class CustomAutoCloseable implements AutoCloseable {

    public static void main(String[] args) {
        try (CustomAutoCloseable autoCloseable = new CustomAutoCloseable()) {
            autoCloseable.start();
        }
    }

    public void start() {
        System.out.println("Start...");
    }

    @Override
    public void close() {
        System.out.println("Closing resource...");
    }
}

The CustomAutoCloseable class implements AutoCloseable interface. In order to implement it correctly we implemented close() method.

Running this code will present the following output:

Start...
Closing resource...

but what will happen when we throw an exception in start() method like in the following example:

public void start() {
   System.out.println("Start...");
   throw new RuntimeException("Something went wrong...");
}

the output will be:

Start...
Closing resource...
Exception in thread "main" java.lang.RuntimeException: Something went wrong...
    at com.frontbackend.java.io.trywithresources.CustomAutoCloseable.start(CustomAutoCloseable.java:13)
    at com.frontbackend.java.io.trywithresources.CustomAutoCloseable.main(CustomAutoCloseable.java:7)

In this case close() method was also called even when an exception occurs. This is because it works like a finally statement.

5. Conclusion

In this article, we presented how to use the try-with-resources statement in Java. Before version 7 of Java, we had to use the finally blocks to clean up the resources. Java 7 gives the opportunity to automatically close the resources that implemented the AutoCloseable interface. Cleanup is initialized by JVM by calling the close() method as soon as the try-with-resources block finishes.

{{ message }}

{{ 'Comments are closed.' | trans }}