파일 업로드 코드를 작성하던 와중에, try-catch의 try에 파라미터가 들어가는 것을 보았다.
try-catch 구문에서는 항상 catch에서 에러를 잡을 때 파라미터로 잡는 것으로만 파라미터를 봤는데,
try에 파라미터가 있는 것은 처음 보았다.
구글링을 진행해보니 try-with-resource라는 방식이 따로 존재하고 있었다.
자원 해제를 더 쉽게 처리해준다는 장점이 있었다.
얼마나 자원 해제가 쉬워졌는지, 기존 try-catch-finally와 try-with-resources를 비교해보자.
기존 try-catch-finally로 자원 해제
public static void main(String args[]) throws IOException {
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream("file.txt");
bis = new BufferedInputStream(is);
int data = -1;
while((data = bis.read()) != -1){
System.out.print((char) data);
}
} finally {
// close resources
if (is != null) is.close();
if (bis != null) bis.close();
}
}
👉 try문 안에서 FileInputStream 객체를 생성하고 finally에서 자원을 해제하는 것을 알 수 있다.
또한, 자원 해제 시 InputStream 객체의 null 체크와 close에 대한 예외 처리도 진행해야한다.
이러한 번거로움때문에 자바 7에서 try-with-resources가 도입되었다.
자바 7의 try-with-resources
public static void main(String args[]) {
try (
FileInputStream is = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(is)
) {
int data = -1;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
👉 try의 파라미터에 InputStream 객체를 생성했다.
이때, 이렇게 try 파라미터 try(…)에서 생성된 InputStream 객체는 try문을 빠져나갈 때 자동으로
생성된 InputStream 객체의 close() 를 호출하여 자동으로 자원 해제가 된다.
따라서 이전의 번거로운 코드를 제거할 수 있다.
※ Try-with-resources에서 close()가 자동으로 호출되는 객체 : AutoCloseable을 구현한 객체
AutoCloseable을 구현하지 않은 객체는 close()가 호출되지 않는다.
프로젝트 Try-with-resources 코드
try(InputStream inputStream = file.getInputStream()) {
amazonS3Client.putObject(new PutObjectRequest(bucket, fileName, inputStream, objectMetadata)
.withCannedAcl(CannedAccessControlList.PublicRead));
} catch(IOException e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "파일 업로드에 실패했습니다.");
}
👉 InputStream을 try(…)에 생성하여 사용 후 try를 빠져나갈 때 자동으로 자원 해제되도록 했다.
참고
Java - Try-with-resources로 자원 쉽게 해제하기
Java - Try-with-resources로 자원 쉽게 해제하기
try-with-resources는 try(...)에서 선언된 객체들에 대해서 try가 종료될 때 자동으로 자원을 해제해주는 기능입니다. 객체가 AutoCloseable을 구현하였다면 Java는 try구문이 종료될 때 close()를 호출해 줍니
codechacha.com
'하루 작성 Today Project > Study' 카테고리의 다른 글
@CreatedDate Format 변경하기 (0) | 2022.11.02 |
---|---|
LocalDateTime 주요 메소드 정리 (0) | 2022.11.02 |
DTO에 기본 생성자가 필요한 이유 (5) | 2022.11.02 |