Skip to main content

I/O in Java - try-with-resources (Part 3)

This topic is not an ideal part of the I/O in Java but as we saw in the previous post, we need to clean resources after the execution of the task to avoid memory leaks.

A resource is an object that must be closed once our code is done using it. For e.g. a File resource or JDBC resource for a database connection or a Socket connection resource. Before Java 7, there was no auto resource management and it was the responsibility of the programmer to perform resource cleanup (usually using try-catch-finally construct). This caused unforeseen errors in the application.

Then in Java 7, came try-with-resources feature. With this feature, the programmer does not have to worry about explicit closing of resources in the finally block, it is done automatically.

Let us see examples of both the approaches one by one.

The old way (before Java 7)

Below is the typical example of how things were usually done before Java 7 - 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private static void oldWay() {

        // This string variable will hold one line of the file one by one
        String line;

        // Buffered instance to get buffer
        BufferedReader bufferedReader = null;

        try {
            // Creating an instance of FileReader to read the file by providing the path
            FileReader fileReader = new FileReader(filePath);

            // Creating the instance of BufferedReader to read text file
            bufferedReader = new BufferedReader(fileReader);

            while ((line = bufferedReader.readLine()) != null) {

                // Printing the line
                System.out.println(line);
            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            // Close the BufferedReader to avoid memory leaks
            try {

                if (bufferedReader != null) {
                    bufferedReader.close();
                }

            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

You can clearly see that we are creating an instance of the BufferedReader in the try block and it is being explicitly closed in the finally block by the programmer. In case the programmer forgets to perform this cleanup task, memory leaks will be present in the application.

Let's see another approach using try-with-resources - the new and fancy way

The new way (since Java 7)

Since Java 7, we can use the try-with-resources construct to perform the same task in an elegant manner. Let's see how - 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
private static void newWay() {

        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {

            // Variable that holds the current line in the file
            String line;

            while ((line = bufferedReader.readLine()) != null) {

                // Printing the current line
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

As you can see that, this is a much concise and cleaner way to do things. We are creating new resources in the try method in the parenthesis and we do not have to close these resources in the finally block, Java will take care of it. Cool, eh? 🙋

There is one difference to note between try-catch-finally and try-with-resources in case of exceptions.

If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block.

For try-with-resources, if an exception is thrown in the try block and in the try-with-resources statement, then the method returns the exception thrown in the try block.

Conclusion

In this post, we discussed a cool new way of handling resources in Java and saw the differences between the two by means of code snippets.  

You can find the complete code on my GitHub repository.

I would love to hear your thoughts on this and would like have suggestions from you to make it better. 

Feel free to befriend me on FacebookTwitter or Linked In or say Hi by email.

Happy Coding 😊

Comments

Popular posts from this blog

Threads in Java - Masterclass (Part 0)

Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading.
One should exploit this feature, especially with all these multiple core machines nowadays.

Below are a few reasons why we should use multithreading -
1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a processor busy can be a tough task e…

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects -
making connectionscachingretrying failed requeststhreadingresponse parsingerror handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes -  Model class to map the JSON dataInterfaces which defines the possible HTTP operationsRetrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The response is returned as a Call object…

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user.

The output of this UI will be like this -
I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started.
Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml fileNavigate to app\src\main\res\values\styles.xmlChange the style value from DarkActionBar to NoActionBar as below<resources><!-- Base application theme. --><stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark&qu…