K-DigitalTraining 강의/1. Java
JDK7 부터 추가된 try-with-resources 문
이대곤
2023. 1. 19. 18:14
Try-with-resources 는 무엇인가?
try에 자원 객체를 전달하면, try 코드 블록이 끝나면 자동으로 자원을 종료해주는 기능이다.
원래는 힙영역에 동적으로 할당된 자원이 사용되지 않는다면 가비지 컬렉터가 알아서 자원 회수를 하겠지만은 그래도 이 전에 close()로 자원을 회수시켜주면 더 좋을 것이다. 그래서 아래의 코드를 두번째 코드처럼 작성할 수 있다.
Try-with-resources 가 적용되지 않은 코드
SomeResource resource = null;
try {
resource = getResource();
use(resource);
} catch(...) {
...
} finally {
if (resource != null) {
try { resource.close(); } catch(...) { /* 아무것도 안 함 */ }
}
}
Try-with-resources 가 적용된 코드
try (SomeResource resource = getResource()) {
use(resource);
} catch(...) {
...
}
Try-with-resources 가 적용된 코드(여러자원 나열 가능)
try(Something1 s1 = new Something1();
Something2 s2 = new Something2()) {
} catch(...) {
...
}
Try-with-resources 가 적용된 실 예시
public static String getHtml(String url) throws IOException {
URL targetUrl = new URL(url);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(targetUrl.openStream()))){
StringBuffer html = new StringBuffer();
String tmp;
while ((tmp = reader.readLine()) != null) {
html.append(tmp);
}
return html.toString();
}
}