AutoCloseable的作用
平时的开发中,有些对象的使用自身拥有占用部分内存资源,如果只是使用,不去释放的话,可能会发生内存耗尽的异常和错误或者一些其他未知的问题。之前的办法是手动的去close资源。一些资源也实现了该接口,如preparedStatement、Connection、InputStream、outputStream等接口, 那么只要将这些代码实例包含在try{}catch{} 块中就可以自动释放掉。
String sql = "select 1 from dual";
try
(
PreparedStatement pstmt = toConn.prepareStatement(sql);
PreparedStatement pstmt1 = fromConn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
ResultSet rs1 = pstmt1.executeQuery()
)
{
if(rs.next() || rs1.next()){
}
}
catch (SQLException e) {
log.error("test conn fail:", e);
e.printStackTrace();
throw new IllegalStateException("mysql链接发生异常!");
}
这样的话就不需要在 finally 中 写 re.close() 和 pstmt.close()了。