2013-02-13 55 views
14

Eclipse我收到警告Resource leak: 'ps' is not closed at this location,我不明白。eclipse中的資源泄漏警告

在我的Java代碼中,我聲明「ps」作爲預備聲明,我多次使用(並關閉)它。然後,我有以下順序:

try { 
    if(condition) { 
     ps = c.prepareStatement("UPDATE 1 ..."); 
    } else { 
     ps = c.prepareStatement("UPDATE 2 ..."); 
    } 
    ps.executeUpdate(); 
} catch (SQLException e) { 
    // exception handling 
} finally { 
    if (null != ps) 
     try { 
      ps.close(); 
     } catch (SQLException e) { 
      // exception handling 
     }; 
} 

「資源泄漏」 - 警告出現在「更新」 - 其他部分中的語句。 如果我在啓動try塊之前設置了ps = null,則沒有警告。

如果第二個UPDATE語句被註釋掉,則不會顯示警告。

這是理解還是java/eclipse問題?

+1

我的猜測是Eclipse正在檢測到您之前使用了預準備語句對象,並且由於潛在的SQLException可能無法正確關閉它。如果你在finally塊中執行'ps = null;'它可能會被修復,這將是一個更合理的清理它的地方。 – 2013-02-13 20:58:02

回答

3

我認爲,這是您使用的檢查器的問題。

將代碼分解爲initializationuse塊。此外,拋出初始化塊的異常(或做一個提前返回)。這樣,就沒有必要檢查空當你釋放資源後use

// initialization 
// Note that ps is declared final. 
// I think it will help to silence your checker 
final PreparedStatement ps; 

try { 
    if(bedingungen ...) { 
     ps = c.prepareStatement("UPDATE 1 ..."); 
    } else { 
     ps = c.prepareStatement("UPDATE 2 ..."); 
    } 
} 
catch (SQLException e) { 
    log.error("Problem creating prepared statement, e); 
    throw e; 
} 

// use 
try { 
    ps.executeUpdate(); 
} catch (SQLException e) { 
    log.error("Problem decrementing palets on " + srcElement.getName() + 
     ": " + e.getMessage()); 
} 
finally { 
    try { 
     ps.close(); 
    } catch (SQLException e) { 
     log.warn("Error closing PreparedStatement: " + e.getMessage()); 
    }; 
} 
+0

我會試試... – 2013-02-13 21:04:55

10

如果您使用的是Java 7。在這種情況下,這個警告,您不應該關閉實現AutoClosable自己的資源。你應該在statementcommented的try特殊的初始化部分初始化這些資源:

// decide which update statement you need: 
// (your if should be here) 
String update = ....; 
try (
    ps = c.prepareStatement(update); 
) { 
    // use prepared statement here. 
} catch (SQLException) { 
    // log your exception 
    throw new RuntimeException(e); 
} 
// no finally block is needed. The resource will be closed automatically. 

我確實不知道爲什麼if/else聲明的存在導致出現或消失的警告。但是,Java 7推薦使用我上面描述的可自動關閉的資源,所以試試這個。

+0

謝謝,這幫了我。由於我還沒有準備好完全承諾Java 7,我只是告訴Eclipse將資源泄漏設置爲忽略。可能很危險,但現在可以工作。 – rjcarr 2013-02-27 22:02:23

-4

將變量名稱從c更改爲mC。我認爲這是一個奇怪的小故障,而使用c作爲變量名稱。謝謝Charlie