Java) try-with-resources

나가을·2024년 7월 31일
0

java

목록 보기
11/12

try-with-resources 구문과 리소스 관리

1. try-with-resources 구문 소개

1.1 개요

  • try-with-resources 구문은 하나 이상의 리소스를 선언하는 try 구문이다. 리소스는 프로그램이 사용을 마친 후 반드시 닫아야 하는 객체이다.
  • 이 구문은 각 리소스가 구문의 끝에서 자동으로 닫히도록 보장한다.

1.2 사용 가능한 리소스

  • java.lang.AutoCloseable 인터페이스를 구현하는 모든 객체가 리소스로 사용될 수 있다. 여기에는 java.io.Closeable 인터페이스를 구현하는 객체도 포함된다.

2. try-with-resources 구문 예제

2.1 파일에서 첫 번째 줄 읽기

  • BufferedReader를 사용하여 파일에서 첫 번째 줄을 읽는 예제이다.
static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}

2.2 JDBC 예제

  • try-with-resources 구문을 사용하여 java.sql.Statement 객체를 자동으로 닫는 예제이다.
public static void viewTable(Connection con) throws SQLException {
    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
    try (Statement stmt = con.createStatement()) {
      ResultSet rs = stmt.executeQuery(query);
      while (rs.next()) {
        String coffeeName = rs.getString("COF_NAME");
        int supplierID = rs.getInt("SUP_ID");
        float price = rs.getFloat("PRICE");
        int sales = rs.getInt("SALES");
        int total = rs.getInt("TOTAL");
        System.out.println(coffeeName + ", " + supplierID + ", " + price +
                           ", " + sales + ", " + total);
      }
    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    }
}

3. Java SE 7 이전의 리소스 관리

  • Java SE 7 이전에는 리소스를 관리하기 위해 finally 블록을 사용하였다. try-catch-finally 블록을 통해 리소스가 정상적이든 비정상적이든 닫히도록 하였다.

하지만 try-catch-finally로는 finally에서도 오류가 발생할 수 있다...!(즉 리소스 반납이 실패할 수도 있다.)

5. AutoCloseable 및 Closeable 인터페이스

  • AutoCloseable: JDK 7에서 도입된 인터페이스로, Exception을 던질 수 있는 close() 메서드를 포함한다.
  • Closeable: JDK 5에서 도입된 인터페이스로, IOException을 던질 수 있는 close() 메서드를 포함한다. 주로 I/O 스트림과 관련된 작업에서 사용된다.

5.1 Closeable의 구현 예제

import java.io.Closeable;
import java.io.IOException;

public class MyCustomCloseableClass implements Closeable {

    @Override
    public void close() throws IOException {
        // 자원 닫기
        System.out.println("Closing");
    }
}

5.2 try-with-resources 구문에서 Closeable 사용

  • try-with-resources 블록을 사용하여 Closeable 객체를 자동으로 닫을 수 있다.

    	try(이부분에 자원을 할당한다.){
    		이부분에서 자원을 활용한 코드를 작성한다.
    	} 
    	try문이 끝나면 저절로 자원은 반납된다.
import java.io.*;

class Resource {
    public static void main(String s[]) {
        try (Demo d = new Demo(); Demo1 d1 = new Demo1()) {
            int x = 10 / 0;
            d.show();
            d1.show1();
        } catch (ArithmeticException e) {
            System.out.println(e);
        }
    }
}

class Demo implements Closeable {
    void show() {
        System.out.println("inside show");
    }

    public void close() {
        System.out.println("close from demo");
    }
}

class Demo1 implements Closeable {
    void show1() {
        System.out.println("inside show1");
    }

    public void close() {
        System.out.println("close from demo1");
    }
}

출력 결과
(자원은 괄호 안에서 생성된 역순으로 닫히게 된다)
close from demo1
close from demo
java.lang.ArithmeticException: / by zero

6. 적용성 및 결론

  • try-with-resources 구문은 리소스를 올바르게 관리하고 예외를 적절히 처리하는 데 매우 유용하다.
  • 잘못된 리소스 관리는 중요한 예외가 가려지거나 리소스 누수가 발생할 수 있으며, 이는 시스템의 성능 저하 또는 서비스 거부를 초래할 수 있다.
  • 따라서 try-with-resources 구문을 사용하면 예외 처리를 보다 간결하고 안전하게 작성할 수 있다.
profile
도라도라 코딩나라

0개의 댓글