-
아이템 9. try-finally보다는 try-with-resources를 사용하라
자원을 회수하는 방법1. 자원을 직접 close()로 회수하면 놓치기 쉬워서 예측할 수 없는 성능 문제로 이어질 수 있다.2. 안전망으로 finalizer, cleaner를 활용하고 있지만 예측할 수 없고 위험 가능성이 있어 권장하지 않는다. (아이템 8)3. try-finally (Java 7 이전의 finally 방식) ⭐예시 코드
public class MyResource implements AutoCloseable{
public void doSNothing(){
System.out.println("Nothing");
}
public void doSomething(){
System.out.println("Do Something");
throw new FirstError();
}
public void doSomething1(){
System.out.println("Do Something1111");
throw new FirstError();
}
@Override
public void close() throws SecondError {
System.out.println("Close My Resource");
throw new SecondError();
}
}
public class FirstError extends RuntimeException{
public FirstError() {
super("첫 번째 에러입니다.");
}
}
public class SecondError extends RuntimeException {
public SecondError() {
super("두 번째 에러입니다.");
}
}
public class AppRunner {
public static void main(String[] args) {
MyResource myResource = new MyResource();
try {
myResource.doSomething();
} finally {
myResource.close();
}
}
} 실행결과
실행결과
public class Class1 {
public method1() throws Exception {
conn = DBPool.getConnection(); //
stmt = conn.createStatement();
rs = stmt.executeQuery(..);
try {
conn = ...;
ps = ...;
rs = ...;
} catch (Exception e) {
// ...
} finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (ps != null) try { ps.close(); } catch(Exception e) {}
if (conn != null) try { conn.close(); } catch(Exception e) {}
}
}
}
4. try-with-resources (Java 7) ⭐
AutoCloseable ❓classDiagram
AutoCloseable <|-- Closeable
interface Closeable
public interface AutoCloseable {
void close() throws Exception;
}
public interface Closeable extends AutoCloseable {
public void close() throws IOException;
}
❗ 정리
public class AppRunner {
public static void main(String[] args) {
try (MyResource myResource = new MyResource()) {
myResource.doSomething();
}
}
} 실행결과
public class AppRunner {
public static void main(String[] args) {
try (MyResource myResource = new MyResource();
MyResource myResource1 = new MyResource()) {
myResource.doSomething();
myResource1.doSomething();
}
}
} 실행결과
➕ 또한, Java 7에서 추가된 Throwable 의 getSuppressed 메서드를 이용하면 프로그램 코드에서 가져올 수 있다. public class AppRunner {
public static void main(String[] args) {
try (MyResource myResource = new MyResource()) {
myResource.doSomething();
} catch (Throwable e) {
Throwable[] suppExe = e.getSuppressed();
System.out.println("Suppressed Exception Array length = " + suppExe.length);
System.out.println("Message Text = " + suppExe[0].getMessage());
}
}
} 실행결과
5. 항샹된 try-with-resources (Java 9) ⭐ public class AppRunner {
public static void main(String[] args) {
MyResource myResource = new MyResource();
try (myResource) {
myResource.doSomething();
}
}
}
중첩된 자원의 close() 는 어떻게 처리 될까?
try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
} catch (IOException e) {
}
해답▫️ 해답은 try() 문에서 자신의 변수가 아닌 객체의 close()를 자동으로 해주진 않는다. 💡 핵심정리
참고자료 |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 7 replies
-
정리 감사합니다. try-with-resource 구조를 사용하려면 해당 자원이 AutoCloseable 인터페이스를 구현해야 한다. 라고 하셨는데 Closeable 인터페이스를 구현한 객체 또한 try-with-resource 구조를 사용할 수 있는 것으로 알 고 있습니다. |
Beta Was this translation helpful? Give feedback.
-
정리 해 주신글 잘 읽었습니다 👍
|
Beta Was this translation helpful? Give feedback.
-
잘 읽었습니다~! 몇 가지 본 내용을 공유드리자면,
|
Beta Was this translation helpful? Give feedback.
정리 감사합니다. try-with-resource 구조를 사용하려면 해당 자원이 AutoCloseable 인터페이스를 구현해야 한다. 라고 하셨는데 Closeable 인터페이스를 구현한 객체 또한 try-with-resource 구조를 사용할 수 있는 것으로 알 고 있습니다.
AutoCloseable과 Closeable의 차이가 무엇일까요?