我一直在使用VisualVM在我的PC上本地分析我的web應用程序。我很確定我有一個小內存泄漏。在拍攝應用程序的快照後,我選擇了具有最多實例化對象的對象,並查看Allocation Call Tree以查看我是否能夠找到哪個類別(導致「潛在泄漏」)。可能在Java webapp中有內存泄漏 - 有關於垃圾回收和會話屬性的問題
我在樹中發現了三個我的類,並查看了精確定位的方法。
下面是我的一個servlet中的一段代碼(一種方法) - 此方法獲取我想保留在會話中的會話屬性的名稱,並刪除剩餘的部分。
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
stmt = conn.createStatement();
HttpSession session = req.getSession();
getExemptSessionAttributes(Customer_Number,rs,stmt,session);
}//try
catch (Exception e) { }
finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) { ; }
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
}
}//finally
}//post
public void getExemptSessionAttributes(int Customer_Number, ResultSet rs, Statement stmt, HttpSession session) {
try {
rs = stmt.executeQuery("Select Name from exemptsessionattributes");
String[] exemptAttributes = null;
int count = 0;
while(rs.next()) {
count++;
}
rs.beforeFirst();
exemptAttributes = new String[count];
count = 0;
while(rs.next()) {
exemptAttributes[count] = rs.getString(1);
count++;
}
session.setAttribute("ExemptSessionAttributes",exemptAttributes);
//garbage collect
exemptAttributes = null;
}//try
catch(Exception e) {}
}//end
//....
迄今我已完成,因爲仿形我的web應用程序的唯一修改,是增加設置exemptAttributes []對象數組爲空的。
我的問題是 - 如果字符串數組(或任何物體)被設置成一個會話屬性,是否意味着該對象的參考,如果不在代碼設置爲空值,則仍然是「參考'並不會被垃圾收集?
我很高興知道這一點。正如我原先所想的那樣,方法中的對象範圍是局部的,之後就不復存在了,對吧?關於,是的,它在我的web.xml中設置爲20分鐘。 –
katura
2011-01-25 22:48:10
範圍實際上是try {}塊,甚至不是整個方法。包含聲明的最內層的一對大括號定義了範圍。 – Affe 2011-01-25 23:02:33
+1影響。我的疏忽。 – 2011-01-25 23:15:23