Item 9. try-with-resources
try-finally๋ณด๋ค๋
try-with-resources
๋ฅผ ์ฌ์ฉํ๋ผ
์๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์๋ InputStream
, OutputStream
, java.sql.Connection
๊ณผ ๊ฐ์ด close()
๋ฉ์๋๋ฅผ ํธ์ถํ์ฌ ์ง์ ์์์ ํ์ํด์ผ ํ๋ ์์์ด ๋ง๋ค. ์์์ ํ์ํ๋ ๊ฒ์ ํด๋ผ์ด์ธํธ๊ฐ ๋์น๊ธฐ ์ฌ์ด ๋ถ๋ถ์ด๊ธฐ ๋๋ฌธ์ ์ฑ๋ฅ ๋ฌธ์ ๋ก ์ด์ด์ง๋ ๊ฒฝ์ฐ๊ฐ ๋ง๋ค.
๋์ฒด๋ก ์์์ ํ์ํ๊ธฐ ์ํด์ try-finally
๊ตฌ๋ฌธ์ ์ฌ์ฉํ๊ฒ ๋๋ค.
try-finally ์ฌ์ฉ
class Test {
// ํ๋์ ์์์ ํ์ํ๋ ๊ฒฝ์ฐ
static String firstLineOfFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close(); // ์ฌ๊ธฐ์ ๋ฐ์ํ ์์ธ๋ง stack trace์ ๋จ์
}
}
}
์์์ ์ ์ ์๋ฏ์ด try-finally
๋ฌธ๋ฒ์ ์ฝ๋๊ฐ ์ง์ ๋ถํด์ง๊ณ ๊ฐ๋
์ฑ์ด ๋จ์ด์ง๋ ๋ฌธ์ ๊ฐ ์๋ค.
๋ํ try-finally
๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ์์ธ๊ฐ ๋ฐ์ํ์ ๋, finally
๋ธ๋ก ์์ close()
๋ฉ์๋์์๋ ์์ธ๊ฐ ๋ฐ์ํ๋ฉด ์๋์ ์์๋ก ์งํ์ด ๋๋ค.
br.readLine()
์์ ์์ธ๊ฐ ๋ฐ์(try
๋ธ๋ก)finally
๋ธ๋ก์ผ๋ก ์ด๋br.close()
์์๋ ์์ธ๊ฐ ๋ฐ์(finally
๋ธ๋ก)br.close()
์ ์์ธ๊ฐbr.readLine()
์ ์์ธ๋ฅผ ๋ฎ์ด์๊ฒฐ๊ณผ์ ์ผ๋ก stack trace์๋
br.close()
์ ์์ธ๋ง ๋จ์
try-with-resources ์ฌ์ฉ
์ ๋ฌธ์ ๋ Java 7์ ๋์จ try-with-resources
๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ํด๊ฒฐํ ์ ์๋ค.
์ด ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด์ ์ฌ์ฉํ๋ ์์(ํด๋์ค)์ด AutoCloseable
์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํด์ผ ํ๋ค.
AutoCloseable
์ธํฐํ์ด์ค
AutoCloseable
์ธํฐํ์ด์คBufferedReader
๋ AutoCloseable
์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํด๋์ ํด๋์ค์ด๋ฉฐ, ๋ง์ ์๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค์ด AutoCloseable
์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํด๋์๋ค.
AutoCloseable
์ธํฐํ์ด์ค์์ close()
๋ฉ์๋๋ฅผ ํ์ธํ ์ ์์ผ๋ฉฐ, ์ด ๋ฉ์๋๋ฅผ ํตํด ์์์ ํ์ํ๋ค.

public interface AutoCloseable {
/**
* Closes this resource, relinquishing any underlying resources.
* -> ์ด ์์์ ํ์ํ๊ณ , ๊ด๋ จ๋ ํ์ ์์๋ค๋ ํ์ํ๋ค.
* This method is invoked automatically on objects managed by the
* {@code try}-with-resources statement.
* -> ์ด ๋ฉ์๋๋ try-with-resources ๋ฌธ์ผ๋ก ๊ด๋ฆฌ๋๋ ๊ฐ์ฒด์์ ์๋์ผ๋ก ํธ์ถ๋ฉ๋๋ค.
*
* ...
*/
void close() throws Exception;
}
try-with-resources
๊ตฌ๋ฌธ
try-with-resources
๊ตฌ๋ฌธ๊ธฐ์กด ์ฝ๋์ try-with-resources
๊ตฌ๋ฌธ์ ์ ์ฉํ๋ฉด ๋ค์๊ณผ ๊ฐ๋ค.
class Test {
static String firsLineOfFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} catch (IOException e) {
throw e;
} finally {
System.out.println("finally");
}
}
}
์ ์ ์คํ
try
๋ธ๋ก ์์์BufferedReader
๊ฐ์ฒด ์์ฑtry
๋ธ๋ก ์์์BufferedReader
๊ฐ์ฒด์readLine()
๋ฉ์๋๋ฅผ ํธ์ถfinally
๋ธ๋ก ์ํfinally
๋ธ๋ก ์คํ ํAutoCloseable
์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํclose()
๋ฉ์๋๋ฅผ ํธ์ถ
์์ธ ๋ฐ์
try
๋ธ๋ก ์์์BufferedReader
๊ฐ์ฒด๋ฅผ ์์ฑtry
๋ธ๋ก ์์์BufferedReader
๊ฐ์ฒด์readLine()
๋ฉ์๋๋ฅผ ํธ์ถreadLine()
๋ฉ์๋์์ ์์ธ ๋ฐ์catch
๋ธ๋ก ์ง์ ํ์ฌ ์์ธ ์ฒ๋ฆฌ(์๋ ๊ฒฝ์ฐ ์์ ํธ์ถ ์คํ์ผ๋ก ์ ํ)finally
๋ธ๋ก ์ํfinally ๋ธ๋ก ์คํ ํ
AutoCloseable
์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํclose()
๋ฉ์๋๊ฐ ํธ์ถclose()
๋ฉ์๋์์๋ ์์ธ๊ฐ ๋ฐ์ ์ ์ด ์์ธ๋ ๋ณ๋ ์ฒ๋ฆฌ ๋จ
๊ฒฐ๊ณผ์ ์ผ๋ก ์์ธ ๋ฐ์ ์ realLine์์ ๋ฐ์ํ ์์ธ๊ฐ close()
๋ฉ์๋์์ ๋ฐ์ํ ์์ธ๋ฅผ ๋ฎ์ด์ฐ์ง ์๋๋ค.
close()
์์ ๋ฐ์ํ ์์ธ๋ ๋ณ๋๋ก ์ฒ๋ฆฌ๋๊ธฐ ๋๋ฌธ์ stack trace์๋ readLine()
์์ ๋ฐ์ํ ์์ธ๋ง ๋จ๊ฒ ๋๊ณ ,
close()
์์ ๋ฐ์ํ ์์ธ๋ getSuppressed()
๋ฉ์๋๋ฅผ ํตํด ํ์ธํ ์ ์๋ค.
Last updated
Was this helpful?