结果即使我关闭RS,也会设置资源泄漏?

时间:2016-07-01 22:56:48

标签: java resultset try-catch-finally resource-leak

我得到了资源泄漏:' rsHP'在这个位置没有关闭'我到处使用rsHP = stmt.executeQuery(查询);

以下是此方法的基本布局......

public static void method(String x, Connection conn){
Statement stmtHP = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
ResultSet rsHP = null;

try{
      ----ALGORITHM IN HERE------
      ****This is the general form of this method*****

      queryHP = "select * from SOMETABLE where SOMETHING = 'blah'";
      rsHP = stmtHP.executeQuery(queryHP);

      while(rsHP.next()){
            List.add(rsHP.getString("COLNAME"));
      }  
            .
            .
        repeats for 8 different queries
            .
            .   
      queryHP = "select * from SOMEOTHERTABLE where SOMETHINGELSE = 'blah2'";
      rsHP = stmtHP.executeQuery(queryHP);

      while(rsHP.next()){
            List.add(rsHP.getString("NEWCOLNAME"));
      } 

}catch(Exception e){
       System.out.println("Hey dumbo you suck, Exception Found");
       rsHP.close();
       stmtHP.close();
       conn.close();
}finally{
       rsHP.close();
       stmtHP.close();
       // connection gets closed later if no exceptions thrown
}

}// end method

最后,我显然已经关闭了所有的东西。我很困惑,如果我的方法无法在不抛出错误的情况下关闭RS而终止我的内存泄漏。

1 个答案:

答案 0 :(得分:1)

Connection#createStatement()抛出一个SQLException,因此这段代码根本不会编译。

我建议你将方法的签名改为

public static void method(String x, Connection conn) throws SQLException

对于资源泄漏,我猜使用以下逻辑会帮助你

try{
    // code
    rsHP.close();
    conn.close();
}catch(Exception e){
    // StackTrace
}finally{
    if (rsHP != null) rsHP.close();
    if (conn != null) conn.close();
}