ITEM 9: try-with-resources
์๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์๋ close
๋ฉ์๋๋ฅผ ํธ์ถํด ์ง์ ๋ซ์์ค์ผํ๋ ์์๋ค์ด ๋ง๋ค.(InputStream
, OutputStream
, java.sql.Connection
๋ฑ) ์์ ๋ซ๊ธฐ๋ ํด๋ผ์ด์ธํธ๊ฐ ๋์น๊ธฐ ์ฌ์ ์์ธกํ ์ ์๋ ์ฑ๋ฅ ๋ฌธ์ ๋ก๋ ์ด์ด์ง๋ค. ์ด๋ฌํ ๊ฒฝ์ฐ ์๋น์๊ฐ ์์ ๋ง์ผ๋ก finalizer
๋ฅผ ํ์ฉํ๊ณ ์์ง๋ง, finalizer
๋ ๋ฏฟ์๋ง ํ์ง ๋ชปํ๋ค.(item 8)
์ ํต์ ์ผ๋ก ์์์ด ์ ๋๋ก ๋ซํ์ ๋ณด์ฅํ๋ ์๋จ์ผ๋ก try-finally
๊ฐ ์ฌ์ฉ๋์๋ค.
static String firstLineOfFile(String path) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(path));
try{
return br.readLine();
}finally {
br.close();
}
}
๊ธฐ๊ธฐ์ ๋ฌผ๋ฆฌ์ ์ธ ๋ฌธ์ ๊ฐ ์๊ฒจ firstLineOfFile
๋ฉ์๋ ์์ readLine
๋ฉ์๋๊ฐ ๋ฌธ์ ๊ฐ ์๊ธด๋ค๋ฉด readLine()
๋ฉ์๋๊ฐ ์์ธ๋ฅผ ๋์ง๊ณ , ๊ฐ์ ์ด์ ๋ก close
๋ฉ์๋๋ ์คํจํ ๊ฒ์ด๋ค. ์ด๋ฌํ ์ํฉ์์ ๋๋ฒ์งธ ์์ธ๊ฐ ์ฒซ๋ฒ์งธ ์์ธ๋ฅผ ์ผ์ผ, ์คํ ์ถ์ ๋ด์ญ์ ์ฒซ๋ฒ์งธ ์์ธ์ ๋ํ ์ ๋ณด๋ ๋จ์ง ์๊ฒ ๋๋ค. ๋ ๋ฒ์งธ ์์ธ ๋์ ์ฒซ ๋ฒ์งธ ์์ธ๋ฅผ ๋จ๊ธธ ์๋ ์์ง๋ง, ์ฝ๋๊ฐ ๋๋ฌด ์ง์ ๋ถํด์ ธ์ ์ค์ ๋ก ๊ทธ๋ ๊ฒ ํ๋ ๊ฒฝ์ฐ๋ ๊ฑฐ์ ์๋ค.
์ด๋ฌํ ๋ฌธ์ ๋ค์ java 7์ try-with-resources
๋์ ๋ชจ๋ ํด๊ฒฐ๋์๋ค. try-with-resources
๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ํด๋น ์์์ด AutoCloseable
์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํด์ผํ๋๋ฐ, ์ ๋ง์ ์ธํฐํ์ด์ค๊ฐ ์ด๋ฏธ AutoCloseable
์ ๊ตฌํํ๊ฑฐ๋ ํ์ฅํด๋์๋ค.
static String firstLineOfFile(String path) throws IOException{
// try - with - resources
try(BufferedReader br = new BufferedReader(new FileReader(path)){
return br.readLine();
}
}
readLine()
๊ณผ close()
ํธ์ถ ์์ชฝ์์ ์์ธ๊ฐ ๋ฐ์ํ๋ฉด, close
์์ ๋ฐ์ํ ์์ธ๋ ์จ๊ฒจ์ง๊ณ , readLine
์์ ๋ฐ์ํ ์์ธ๋ง ๊ธฐ๋ก์ด ๋๋ค. ๋ํ, ์จ๊ฒจ์ง ์์ธ๋ค๋ ์คํ์ถ์ ๋ด์ญ์ suppressed๋ผ๋ ๊ผฌ๋ฆฌํ๋ฅผ ๋ฌ๊ณ ์ถ๋ ฅ๋๋ฉฐ, Throwable
์ ์ถ๊ฐ๋ getSuppressed
๋ฉ์๋๋ฅผ ์ด์ฉํด ํ๋ก๊ทธ๋จ ์ฝ๋์์๋ ๊ฐ์ ธ์ฌ ์ ์๋ค.
static void copy(String src, String dst) throws IOException{
try(InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst))
{
byte[] buf = new byte[BUFFER_SIZE];
int n;
while((n = in.read(buf))>= 0)
out.write(buf, 0, n);
}
}
try - with -resources
try (SomeResource resource = getResource()) {
use(resource);
} catch(...) {
...
}
try์ ์์ ๊ฐ์ฒด๋ฅผ ์ ๋ฌํ๋ฉด, try ์ฝ๋ ๋ธ๋ก์ด ๋๋๋ฉด ์๋์ผ๋ก ์์์ ์ข
๋ฃํด์ฃผ๋ ๊ธฐ๋ฅ์ผ๋ก ๋ฐ๋ก finally
๋ธ๋ก์ด๋ ๋ชจ๋ catch
๋ธ๋ก์ ์ข
๋ฃ ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ์ง ์์๋ ๋๋ค.
ํ์ง๋ง, ์ด ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ํด๋น ์์์ด AutoCloseable
์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํด์ผํ๋ค.
public interface AutoCloseable {
void close() throws Exception;
}
๋ํ, try์์ ๋ณต์์ ์์ ๊ฐ์ฒด๋ฅผ ์ ๋ฌํ ์๋ ์๋ค.
try(Something1 s1 = new Something1();
Something2 s2 = new Something2()) {
} catch(...) {
...
}
static void copy(String src, String dst) throws IOException{
try(InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst))
{
byte[] buf = new byte[BUFFER_SIZE];
int n;
while((n = in.read(buf))>= 0)
out.write(buf, 0, n);
}
}
์ฆ, ๊ผญ ํ์ํด์ผ ํ๋ ์์์ ๋ค๋ฃฐ ๋๋ try-finally
๋ง๊ณ try-with-resources
๋ฅผ ์ฌ์ฉํด๋ผ. ์ฝ๋๋ ๋ ์งง๊ณ ๋ถ๋ช
ํด์ง๋ฉฐ, ๋ง๋ค์ด์ง๋ ์์ธ์ ๋ณด๋ ํจ์ฌ ์ ์ฉํ๋ค. ์ ํํ๊ณ ์ฝ๊ฒ ์์์ ํ์ํ ์ ์๋ค.
์ฐธ๊ณ
Last updated
Was this helpful?