TIL: 2024/05/16

White 와잇·2024년 5월 16일

TIL

목록 보기
20/40
post-thumbnail

try-with-resource

참고 페이지: (https://www.baeldung.com/java-try-with-resources)

  • Java 7부터 지원하는 기능
  • try {} 블록을 실행하고 끝나면 자동으로 리소스를 닫게(.close()) 해주는 방법
  • 메모리 누수 방지를 위함
  • 선언된 리소스는 AutoCloseable 인터페이스 구현해야 함

사용법

  • try 부분에 리소스 선언과 동시에 초기화
try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
    writer.println("Hello World");
}
  • final로 선언된 리소스 혹은 Effectively Final(명시적 final은 아니지만 참조 변경이 없어 실질적으로 final인) 리소스
final Scanner scanner = new Scanner(new File("testRead.txt"));
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))
try (scanner;writer) { 
    // omitted
}

여러 리소스를 사용할 때

try (
	Scanner scanner = new Scanner(new File("testRead.txt"));
    PrintWriter writer = new PrintWriter(new File("testWrite.txt"))
    )

세미콜론으로 구별가능

자동 close 인터페이스 구현

public class MyResource implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("Closed MyResource");
    }
}

AutoCloseable 또는 Closeable 인터페이스를 implements 하고
close() 메서드 재정의(@Override)가 필요하다

코드 비교

  • 일반적인 try-catch-finally
Scanner scanner = null;
try {
    scanner = new Scanner(new File("test.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
        scanner.close();
    }
}
  • try-with-resource (코드도 줄어들었네!)
try (Scanner scanner = new Scanner(new File("test.txt"))) {
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}
profile
웹개발 도전! 데브옵스 도전!

0개의 댓글