AutoCloseable — 자동 닫기 인터페이스
AutoCloseable — 자동 닫기 인터페이스
AutoCloseable은 닫힐 때까지 리소스(파일이나 소켓 핸들 등)를 보유할 수 있는 객체를 나타냅니다. AutoCloseable 객체의 close() 메서드는 해당 객체가 try-with-resources 블록의 리소스 사양 헤더에 선언된 경우 블록을 빠져나갈 때 자동으로 호출됩니다.
본문
이 구조는 리소스를 신속하게 해제하도록 보장하여, 그렇지 않으면 발생할 수 있는 리소스 고갈 예외와 오류를 피하게 해줍니다.
public interface AutoCloseable
메서드
void close() throws Exception
close()는 리소스를 닫아 관련 시스템 리소스를 해제합니다. try-with-resources 블록이 끝나면 자동으로 호출됩니다.
예를 들어 다음 코드에서 try 블록이 끝나면 BufferedReader의 close()가 자동으로 호출됩니다.
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
// 작업
}
Closeable은 AutoCloseable의 특수화로, 입출력 스트림에 대해 close()가 IOException을 던지도록 규정합니다.