Java
[Effective Java] 아이템 9. try-finally보다는 try-with-resources를 사용하라.
quedevel
2022. 5. 24. 10:38
728x90
반응형
- close 메서드를 직접 호출하여 닫아주는 자원들이 존재하기 때문에 클라이언트가 놓치기가 쉽다.
- 안전망으로 finalizer를 활용하고 있지만 [아이템8]에서 말했듯 믿을게 못된다.
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 블록 모두 발생할 수 있다.
- 스택 추적 내역에 첫 번째 예외에 관한 정보는 남지 않게 되어, 실제 시스템에서의 디버깅을 몸시 어렵게 한다.
- 코드가 너무 지저분하다.
// 복수의 자원을 처리하는 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로는 정확하고 쉽게 자원을 회수할 수 있다.
참고 자료
Joshua Bloch, 『Effective Java 3/E』, 개앞맵시 옮김, 프로그래밍인사이트(2018)
http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9788966262281&orderClick=LEa&Kc=
728x90
반응형