본문 바로가기
IO

1. Closeable & Flushable

by 이석준석이 2021. 3. 18.

 

public abstract class InputStream implements Closeable {}
public abstract class OutputStream implements Closeable, Flushable {}

두 클래스모두 Closeable 을 구현하고있다. Closeable은 무엇일까?


1. Closeable

  • Object 의 관련된 모든 데이터스트림을 닫고, 자원을 release 하는 역할을 한다.
public interface Closeable extends AutoCloseable {}

데이터스트림 :

  • 어느 한쪽에서 다른 쪽으로 데이터를 전송하기위한 통로
  • 간단하게 FIFO 형태의 큐라고 생각하면 된다.


2. AutoCloseable

  • try-with-resources block 이 종료되는 경우, 자동으로 close() 메소드를 호출한다.
  • 더 구체적인 Exception 을 던지는 것을 권고한다.
    • AutoCloseable Interface 는 그냥 Exception 을 던지도록 하였으나, 더 구체적으로 던지는 것을 권고한다.
    • 절대 실패할리가 없다면, Exception을 던지지 않도록 구현하자
  • 몇번 close() 를 해도 idempotent 하다.
public interface AutoCloseable {
    void close() throws Exception;
}

throws Exception : 리소스가 해제될 수 없는 경우에 던져진다.


간단한 예시

  • implements Closeable 을 해도 같은 결과를 나타낸다. (Closeable extends AutoCloseable)
@Slf4j
public class CloseableTest {

    public static void main(String[] args) {
        try (AutoCloseableImpl ac = new AutoCloseableImpl("sjlee")) {
            log.info("try {}");
        } catch (Exception e) {
            log.info("catch {}");
            e.printStackTrace();
        }
        log.info("finish");
    }

    @Getter
    @AllArgsConstructor
    static class AutoCloseableImpl implements AutoCloseable {

        String name;

        @Override
        public void close() {
            log.info(name);
        }
    }
}

출력 결과

09:51:11.195 [main] INFO me.sjlee.practicejava.io.CloseableTest - try {}
09:51:11.197 [main] INFO me.sjlee.practicejava.io.CloseableTest - sjlee
09:51:11.197 [main] INFO me.sjlee.practicejava.io.CloseableTest - finish

3. Flushable

 

OutputStream 이 implements 하고 있으며, flush() 메소드가 호출되면, OutputStream 에 저장한 데이터를 Flush 하여 file 이나 console 등, 기록할 파일에 write 됩니다.

 

public interface Flushable {
    void flush() throws IOException;
}

 

 

'IO' 카테고리의 다른 글

2. InputStream&OutputStream&Socket  (0) 2021.03.19