seon99il

Java

Java의 try-with-resources로 메모리 누수 방지하기

3분 소요

java : 7 or higher

개요

Java에서는 상황에 따라 예외 처리를 위해 try-catch-finally를 사용합니다. 그런데 try-catch-finally 구문은 예외 처리뿐 아니라 리소스를 안전하게 닫을(close) 수 있게 해 줍니다.

try-catch-finally 구문을 사용했을 때의 리소스 반환 결과를 확인한 다음, Java 7 이후에 추가된 try-with-resources 구문을 살펴보겠습니다.

try-catch-finally를 사용할 때와 사용하지 않을 때의 차이

사용 후 반환해야 하는 리소스는 Closeable 인터페이스를 구현하고 있으며, 사용 후에는 close 메서드를 호출해야 했습니다.

간단한 예제로 차이를 알아보겠습니다.

데이터베이스 커넥션으로 사용자를 등록하는 메서드

/*
* 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
    }

두 코드는 똑같이 동작합니다! 데이터베이스에서 커넥션을 얻고, 사용자를 등록하고, 커넥션을 정상적으로 닫습니다(반환합니다).

에러가 발생하기 전까지는!

코드 중간에 에러가 발생하면 두 코드의 차이가 분명해집니다.

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
    }

이런 일이 발생하면 아래에 있는 ps, c를 닫는 코드가 실행되지 않아 메모리 누수가 발생합니다.

반환해야 하는 리소스를 사용한다면, 리소스 누수를 막기 위해 try-catch-finally 구문으로 안전하게 리소스를 반환해야 합니다.

Try-with-Resources

앞에서 try-catch-finally로 리소스를 안전하게 반환하는 방법을 배웠습니다.

하지만 몇 가지 단점도 있습니다.

  • 리소스 반환 때문에 코드가 복잡해집니다
  • 실수로 리소스를 반환하지 못하는 경우가 있습니다
  • 번거롭습니다

그래서 이런 문제들을 해결하기 위해 Java 7부터 리소스를 자동으로 반환하는 try-with-resources 구문이 추가되었습니다.

Java는 try-with-resources를 AutoCloseable 인터페이스를 구현한 리소스에 적용할 수 있게 했고, 덕분에 코드가 유연해지고 에러를 놓치지 않고 모든 에러를 잡을 수 있습니다.

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)
        }
    }

이렇게 코드를 작성하면 다음과 같은 이점을 얻을 수 있습니다.

  • 번거로운 리소스 반환 작업을 하지 않아도 됩니다
  • 실수로 리소스를 반환하지 못하는 일을 막을 수 있습니다
  • 에러로 인해 리소스를 반환하지 못하는 일을 방지합니다

이전 글

전체 글 보기 →

댓글