ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바 try-with-resources 알아보기
    Java 2023. 10. 9. 17:41

    try-with-resources

    • try(...)에서 선언된 객체들에 대해 try가 종료될 때 자동으로 자원을 해제해주는 기능
    • try에서 선언된 객체가 AutoCloseable을 구현하였다면 Java는 try구문이 종료될 때 객체의 close() 메소드를 호출

     

    try-catch-finally와 비교

    // IOException를 throws한다고 명시적으로 선언했기 때문에 close에 대한 try-catch 구문을 작성안함
    public static void main(String args[]) throws IOException {
        FileInputStream is = null;
        BufferedInputStream bis = null;
        try {
            is = new FileInputStream("file.txt");
            bis = new BufferedInputStream(is);
            int data = -1;
            while((data = bis.read()) != -1){
                System.out.print((char) data);
            }
        } finally {
            // close resources
            if (is != null) is.close();
            if (bis != null) bis.close();
        }
    }
    • try에서 InputStream 객체를 생성하고 finally에서 close
    • try 안의 코드를 실행하다 Exception이 발생하는 경우 모든 코드가 실행되지 않을 수 있기 때문에 finally에 close 코드를 넣어야 한다.
    • InputStream 객체가 null인지 체크해줘야 하며 close에 대한 Exception 처리도 해야한다.

    위 코드를 try-with-resources구문으로 변환

    public static void main(String args[]) {
        // try(...) 안에 InputStream 객체 선언 및 할당하였습니다. 
        // 여기에서 선언한 변수들은 try 안에서 사용할 수 있습니다.
        try (
            FileInputStream is = new FileInputStream("file.txt");
            BufferedInputStream bis = new BufferedInputStream(is)
        ) {
            int data = -1;
            while ((data = bis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    • try-with-resources에서 자동으로 close가 호출되는 것은 AutoCloseable을 구현한 객체에만 해당
      • AutoCloseable은 인터페이스이며 자바7부터 지원합니다.
    • 코드의 실행 위치가 try 문을 벗어나면 try-with-resources는 try(...) 안에서 선언된 객체의 close() 메소드들을 호출해 finally에서 close()를 명시적으로 호출해줄 필요가 없음

     

    AutoCloseable 구현하는 클래스 만들기

    public static void main(String args[]) {
        try (CustomResource cr = new CustomResource()) {
            cr.doSomething();
        } catch (Exception e) {
        }
    }
    
    private static class CustomResource implements AutoCloseable {
        public void doSomething() {
            System.out.println("Do something...");
        }
    
        @Override
        public void close() throws Exception {
            System.out.println("CustomResource.close() is called");
        }
    }
    
    /*
    출력 결과
    Do something...
    CustomResource.close() is called
    */

     

     

     

    출처)

    https://codechacha.com/ko/java-try-with-resources/

Designed by Tistory.