seon99il

Java

Preventing memory leaks using try-with-resources in Java

3 min read

java : 7 or higher

Overview

Depending on the situation, we use try-catch-finally for exception handling in Java. But the try-catch-finally syntax gives you the ability to safely close resources in addition to handling exceptions.

Let’s check the result of the resource return based on the use of the try-catch-finally syntax, and then take a look at the try-with-resources syntax added in Java 7 and later.

The difference between using try-catch-finally and not using it

Resources that need to be returned after use implement the Closeable interface, and you had to call the close method after use.

I’ll use a simple example to find out the difference.

Method to register a user through a database connection

/*
* A method of saving user with Try-catch-finally
*/
public void addUserWithTryCatch(User user) throws ClassNotFoundException, SQLException {
        Connection c = null;
        PreparedStatement ps = null;
        try {
            Class.forName("org.h2.Driver");
            c = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa", "");
            ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");
            ps.setString(1, user.getId());
            ps.setString(2, user.getName());
            ps.setString(3, user.getPassword());

            ps.executeUpdate();
        } finally {
            if (ps != null) ps.close(); // close PreparedStatement
            if (c != null) c.close(); // close Connection
        }
    }

public void addUser(User user) throws ClassNotFoundException, SQLException {
        Connection c = null;
        PreparedStatement ps = null;
        Class.forName("org.h2.Driver");
        c = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa", "");
        ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");
        ps.setString(1, user.getId());
        ps.setString(2, user.getName());
        ps.setString(3, user.getPassword());

        ps.executeUpdate();
        if (ps != null) ps.close(); // close PreparedStatement
        if (c != null) c.close(); // close Connection
    }

Both codes work the same! They get connections from the database, register users, and close (return) connections as normal.

Until an error occurs!

If an error occurs in the middle of the code, the difference between the two codes becomes clear.

public void addUser(User user) throws ClassNotFoundException, SQLException {
        Connection c = null;
        PreparedStatement ps = null;
        Class.forName("org.h2.Driver");
        c = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa", "");
        ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");
        ps.setString(1, user.getId());
        ps.setString(2, user.getName());
        ps.setString(3, user.getPassword());

        ps.executeUpdate(); // Error occur! : Duplicated userId

        if (ps != null) ps.close(); // not running & not closing
        if (c != null) c.close(); // not running & not closing
    }

If this happens, the code that closes ps and c below is not executed and a memory leak occurs.

If we use a resource that needs to be returned, to prevent resource leakage we should return the resource safely using the try-catch-finally syntax.

Try-with-Resources

Earlier, we learned how to safely return a resource using try-catch-finally.

But there are also some cons.

  • Code is complicated by resource returns
  • There are cases where you can’t return the resource by mistake
  • It is cumbersome

So, to solve these issues, the try-with-resources syntax, which automatically returns resources, has been added since Java 7.

Java made try-with-resources applicable to resources that implement the AutoCloseable interface, which makes the code flexible and can catch all errors without missing any.

public void addUserWithTryResources(User user) throws ClassNotFoundException, SQLException {
        try (
            Class.forName("org.h2.Driver");
            c = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa", "");
            ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");

        ){
            ps.setString(1, user.getId());
            ps.setString(2, user.getName());
            ps.setString(3, user.getPassword());

            ps.executeUpdate();
            // return resources (c, ps)
        }
    }

By writing code in this way, you can get the following benefits:

  • You don’t have to do the cumbersome resource return work
  • Can prevent accidentally failing to return resources
  • Prevents failure to return resources due to errors

Previous posts

View all posts →

Comments