try-with-resources in Java 7

Java 7 brought great features for lazy Java developers. Try-with-resources in Java 7 is one of those functions that shortens the line of code and makes the code more robust. In this tutorial, I’ll be discussing things around this feature.

The old way of cleaning up resources (before Java 7)

For example. read a file from the file system. The code might look different, but the flow is like the following example:

public class Resource_Management_Before_Java7 
{
    public static void main(String[] args) 
    {
        BufferedReader br = null;
        try
        {
            String sCurrentLine;
            br = new BufferedReader(new FileReader("C:/temp/test.txt"));
            while ((sCurrentLine = br.readLine()) != null) 
            {
                System.out.println(sCurrentLine);
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (br != null)
                    br.close();
            } 
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

These types of code are very common in an application code base with many I / O operations.

The code within the try and catch blocks is essentially important and has application-specific logic. Final blocks are simply copping and paste to save resources from corruption by shutting them down.
Java 7 solves this problem with the try-with-resources function.

The sophisticated new way of using try-with resources (example syntax)

Now, let’s take a look at the new method of opening and closing a resource in Java 7

public class Resource_Management_In_Java7 
{
    public static void main(String[] args) 
    {
        try (BufferedReader br = new BufferedReader(new FileReader("C:/temp/test.txt")))
        {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) 
            {
                System.out.println(sCurrentLine);
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

There are two things to look out for:

The file resource (BufferedReader) is open and in a try block in a special way (in brackets). Eventually, the block disappeared completely.
Finally, the code is nice and easy to read.

How does it actually work?

In Java 7 we have a great new java.lang.AutoCloseable interface. This interface has a method:

void close() throws Exception;

The Java documentation recommends implementing this interface on any resource and that should be close when it is no longer needed. If we open such an AutoCloseable resource in the special try-with-resource block, the JVM calls this close() method for all resources that were initialized in the try() block immediately after the try block has been completed.

For example, BufferedReader has implemented the following close () method file:

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        in.close();
        in = null;
        cb = null;
    }
}

Due to the method defined above, any underlying streams or I/O resources will be closed when this method is called by the JVM.

Adding functions to custom resources

Well, that is a good resource cleaning design. But is it only available for native JDK classes? NO. You can also use it for your custom resources.

For example, in the following code, I created a custom resource:

public class Custom_Resource implements AutoCloseable 
{
    public void accessResource() {
        System.out.println("Accessing the resource");
    }
     
    @Override
    public void close() throws Exception {
        System.out.println("CustomResource closed automatically");
    }
}

Now I am using it in my example code:

public class Try_With_Custom_Resource 
{
    public static void main(String[] args)
    {
        try(CustomResource cr = new CustomResource())
        {
            cr.accessResource();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
 
Putput in console:
 
Accessing the resource
CustomResource closed automatically

The output to the console clearly proves that the resource was automatically closed as soon as they try block was completed.

Closing remarks

Here everything revolves around automatic resource management with try-with-resources in Java 7. Let’s take a look at the highlights point by point:

  • Before Java 7, we had to use finally blocks to clean up resources. Eventually, the blocks weren’t needed, but cleaning up the resources had to prevent damage to the system.
  • With Java 7, no explicit resource cleanup is required. It just happens automatically.
  • The automatic resource cleanup is carried out when the resource is initialized in the try-with-resources block (try (…) {…}).
  • The cleanup is based on the new AutoCloseable interface. Its close method is called by the JVM as soon as they try block ends.
  • If you want to use it in custom resources, the implementation of the AutoCloseable interface is mandatory. otherwise, the program will not be compiled.
  • You shouldn’t call the close () method in your code. This should be called automatically by the JVM. A manual call can lead to unexpected results. 2
Please share this post:
Posts created 45

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: