close메서드를 통해 직접 닫아줘야 하는 자원이많다
자원닫기는 클라이언트가 놓치기 쉬워서 예측할수없는 성능 문제로 이어지기도한다.
상당수가 finalizer를 활용하고있지만 적절한 방법은 아니다
1.자원을 회수하는 최선책- try-with-resources
static String firstLineOfFile(String path) throws IOException{
try(BufferedReader br= new BufferedReader(new FileReader(path))){
return br.readLine();
}
}
1)try-with-resource버전이 짧고 읽기 수월할뿐아니라 문제를 진단하기도 훨씬좋다.
2)보통의 try-finally에서처럼 catch절을 쓸수있다
-catch절덕분에 try문을 중첩하지 않고도 다수의 예외처리 가능
try-with-resources를 catch절과 함께 쓰는 모습
static String firstLineOfFile(String path,String defalutVal){
try(BufferedReader br= new BufferedReader(new FileReader(path))){
return br.readLine();
}catch (IOException e){
return defalutVal;
}
}