Skip to content

Latest commit

ย 

History

History
45 lines (33 loc) ยท 1.31 KB

File metadata and controls

45 lines (33 loc) ยท 1.31 KB

try-with-resource

์ „ํ˜•์ ์ธ try-catch-finally ๊ตฌ๋ฌธ์„ ์‚ฌ์šฉํ•œ Stream ์ฒ˜๋ฆฌ ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

try {
  InputStream in = connection.getInputStream(); 
  OutputStream out = connection.getOutputStream();
  
  ... 
  ...
    
} catch (IOException e) {
  log.error(e.getMessage());
} finally {
  if(out != null) {
    try { 
      out.close();
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  }
}

finally ๊ตฌ๋ฌธ์€ try ๊ตฌ๋ฌธ์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ, ์—ด๋ฆฐ stream์„ ๋‹ซ์•„ Memory Leak์„ ๋ฐฉ์ง€ํ•œ๋‹ค. ํ•˜์ง€๋งŒ, ์œ„์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์€ ์‹ค์ œ ๊ฐœ๋ฐœ์ž๊ฐ€ ์ž‘์„ฑํ•ด์•ผ ํ•  ์ฝ”๋“œ ๋ณด๋‹ค Stream์— ๋Œ€ํ•œ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•œ ์ฝ”๋“œ๊ฐ€ ๋” ๋งŽ์€ ๋ถ€๋ถ„์„ ์ฐจ์ง€ํ•œ๋‹ค.

Java 7๋ถ€ํ„ฐ try-with-resource ๋ฌธ๋ฒ•์„ ์ ์šฉํ•ด ์ž์›์„ ๋ฐ˜๋‚ฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ๊ฐ€๋Šฅํ•ด์กŒ๋‹ค.

try (InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream()) {
  HttpRequest httpRequest = new HttpRequest(in);
  HttpResponse httpResponse = new HttpResponse(out);

  ...
  ...
    
} catch (IOException e) {
  log.error(e.getMessage());
}

try ์กฐ๊ฑด์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ๊ฒฝ์šฐ ์ž๋™์œผ๋กœ ์—ด์—ˆ๋˜ stream์„ ๋‹ซ์•„์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ๊ธฐ์กด ์ฝ”๋“œ์—์„œ finally ๋ถ€๋ถ„์„ ์ž‘์„ฑํ•˜๋ฉฐ ๋ฐœ์ƒํ–ˆ๋˜ ๋ถˆํ•„์š”ํ•œ ์ฝ”๋“œ๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.