자바 라이브러리에는
close
메서드를 호출해 직접 닫아줘야 하는 자원이 많다.
ex) InputStream
, OutputStream
, java.sql.Connection
등
상당수가 안전망으로 finalizer
를 사용하고 있지만, 믿을만하지 못하다.
try-finally
가 쓰였다.static String firstLineOfFile(final String path) throws IOException {
final BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
}
static void copy(final String src, final String dst) throws IOException {
final 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
문을 제대로 사용한다고 해도, 미묘한 결점이 있다!
firstLineOfFile
메서드 안의 readFile
메서드가 예외를 던지고, 같은 이유로 close
메서드도 실패한다.
<aside>
💡 이러한 문제들은 자바 7에서 등장한 try-with-resources
로 해결할 수 있다!
</aside>
AutoCloseable
인터페이스를 구현해야 한다.
static String firstLineOfFile(final String path) throws IOException {
try (final BufferedReader br = new BufferedReader(
new FileReader(path))) {
return br.readLine();
}
}
static void copy(final String src, final String dst) throws IOException {
try (final 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);
}
}