반응형
java6 이전까지는 close 메서드를 호출하여 안전하게 리소스를 닫아주어야 했다.
x//JAVA6 이전 ...Class.forName("com.mysql.jdbc");try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(jdbcUrl, urerId, passWord); ps = conn.prepareStatement(sql); //.....} catch (SQLException e) { e.printStackTrace();} finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } }}DB connection의 경우 필요한 리소스가 많기 때문에 일일히 리소스를 닫아주는 과정이 번거롭다. JAVA7 부터는 명시적으로 close()를 호출하지 않아도 자동으로 호출하도록 autoclosable을 지원해 준다.
try with resource를 사용하면 자동으로 리소스를 닫는 코드가 호출된다.
xxxxxxxxxxtry (Scanner scanner = new Scanner(new File("test.txt"))) { while (scanner.hasNext()) { System.out.println(scanner.nextLine()); }} catch (FileNotFoundException fnfe) { fnfe.printStackTrace();}여기에서 AutoCloseable이 적용된 클래스들을 확인할 수 있다. Connection과 PrepareStatment, ResultSet을 확인할 수 있다.
xxxxxxxxxxpublic class FileInputStream implements AutoCloseable { private String file; public FileInputStream(String file){ this.file = file; } public void read(){ System.out.println(file+"을 읽습니다."); } public void close() throws Exception { System.out.println(file +"을 닫습니다."); }}이처럼 AutoClosable을 상속받아 필요한 부분에 직접 구현할 수도 있다.
반응형