JDBC释放资源时遇到的问题
在学习JDBC时,看到教学视频的老师释放资源时使用三个try...catch..来关闭,产生了一些疑问。
问题:
为什么要用三个,全部写在一个可不可以。
回答:
不行,例子如下
boolean flag = true; //标志位,标志释放资源是否成功
if(resultSet != null){
try {
resultSet.close();
preparedStatement.close();
con.close();
//GC回收
resultSet = null;
preparedStatement = null;
con = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag = false;
}
}
在上面的代码中,如果前面的.close()发生异常,则会进入到catch里面,剩下的.close()会关闭失败,所以不能这样写。
正确写法:
if(resultSet != null){
try {
resultSet.close();
//GC回收
resultSet = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag = false;
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
//GC回收
preparedStatement = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag = false;
}
}
if(con != null){
try {
con.close();
//GC回收
con = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
flag = false;
}
}
改进:
最后为了保证资源能够释放,还有在每个关闭语句的后面加一个finally,在finally里给要关闭的资源赋值为空。这样就算在关闭过程中抛异常不能及时关闭,但是由于赋值为空,没有引用该资源,在垃圾回收的时候也能够回收。
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally{
//GC回收
resultSet = null;
}
}
if(preparedStatement != null){
try {
preparedStatement.close();
//GC回收
preparedStatement = null;
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally{
//GC回收
preparedStatement = null;
}
}
if(con != null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally{
//GC回收
con = null;
}
}
这样的方法可以确保资源会释放
参考资料:
https://blog.csdn.net/javy_codercoder/article/details/49178529

浙公网安备 33010602011771号