<aside> 💡
자바 라이브러리에는 close
메서드를 호출해 직접 닫아줘야 하는 자원이 많음
ex) InputStream
, OutputStream
, java.sql.Connection
</aside>
finally 에서 수거하면 되지 뭐가 문제야?
public static String firstLineOfFile(String path) throw IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
}
자원이 둘 이상이면 try-finally 방식은 너무 지저분하다!
static void copy(String src, String dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
} finally {
out.close();
}
} finally {
in.close();
}
}
예외는 try 블록과 finally 블록 모두에서 발생할 수 있음(자원을 해제하는 close
메서드를 호출할 때)
이 구조를 사용하려면 해당 자원이 AutoCloseable
인터페이스를 구현해야함
AutoCloseable
: 단순히 void
를 반환하는 close
메서드 하나만 정의한 인터페이스AutoCloseable
을 반드시 구현해야함example
public static String firstLineOfFile(String path) throw IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} catch (Exception e) {
return defaultVal;
}
}
복수의 자원을 처리하는 try-with-resources
static void copy(String src, String dst) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}
}
try-finally 의 문제를 잡아줄 수 있는 try-with-resources 예시
꼭 회수해야 하는 자원을 다룰 때는 try-finally 말고 try-with-resources를 사용하자.
예외는 없다. 코드는 더 짧고 분명해지고, 만들어지는 예외 정보도 훨씬 유용하다.
try-finally로 작성하면 실용적이지 못할 만큼 코드가 지저분해지는 경우라도, try-with-resources로는 정확하고 쉽게 자원을 회수할 수 있음!!