我正在使用mysql-connector-java-5.1.21并且我遇到了内存泄漏,Memory Analyzer 怀疑 java.lang.Class 和mysql.jdbc出现的最大实例之一。我已经浏览了代码并确保所有连接、结果和语句都正确关闭,但我仍然有泄漏。
1,529 instances of "java.lang.Class", loaded by "<system class loader>" occupy 711,632 (41.68%) bytes.
Biggest instances:
•class com.mysql.jdbc.NonRegisteringDriver @ 0x381323f8 - 97,400 (5.70%) bytes.
•class java.io.ObjectStreamClass$Caches @ 0x3d070568 - 91,872 (5.38%) bytes.
•class java.lang.System @ 0x3d03da20 - 67,224 (3.94%) bytes.
•class com.mysql.jdbc.SingleByteCharsetConverter @ 0x382a7438 - 66,032 (3.87%) bytes.
•class java.lang.ref.Finalizer @ 0x3d03e260 - 65,888 (3.86%) bytes.
•class com.sun.org.apache.xerces.internal.util.XMLChar @ 0x380bc528 - 65,592 (3.84%) bytes.
•class com.mysql.jdbc.ConnectionPropertiesImpl @ 0x381ab5f8 - 32,456 (1.90%) bytes.
代码在一个有延迟的循环中运行。目前,代码在每个间隔打开一个连接。我应该只打开一个连接并将其传递给我的方法吗?无论哪种方式,我都不确定为什么会导致泄漏。任何帮助表示赞赏。
这是一些代码,它应该让您对我如何使用 jdbc 和 mysql 有一个很好的了解。
try {
url+=database+"?zeroDateTimeBehavior=convertToNull";
// LatestTime in SQL table defaults 0000-00-00 00:00:00 which java can't handle. zeroDateTimeBehaviour=convertToNull cause JDBC to null for a zero date.
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url,user,password);
System.out.println(CurrentTime()+": "+"Connected to "+database);
}
catch (Exception e)
{
System.err.println(CurrentTime()+": "+e.getMessage());
System.err.println(CurrentTime()+": "+"Unable to Connect");
}
finally
{
if (conn!=null)
{
try {
// Create Statements for SQL queries
Statement query= conn.createStatement();
// Get all records from phonelog which have yet to be processed
query.executeQuery("SELECT * from phonelog where Recordnum>"+Recordnum);
ResultSet rs = query.getResultSet();
// Process each row from query result
while (rs.next()) {
}
JDBCHelper.close(rs);
String plupdate="update Counters set value='"+Recordnum+"' where name='plposition'";
submit.executeUpdate(plupdate);
JDBCHelper.close(query);
}
catch (SQLException SQLe) {
System.err.println(CurrentTime()+": "+SQLe.getMessage());
}
JDBCHelper.close(conn);
System.out.println (CurrentTime()+": "+"Disconnected");
}
}