当我运行在探查下面的代码,我得到一个char []和byte []是累积,直到程序崩溃由于Java堆内存溢出异常。有人能告诉我为什么吗?也许我正在做一些根本错误的事情。噩梦java的泄漏...带环和JDBC
package testleak;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.swing.Timer;
public class TestLeak
{
static String DB_USERNAME = "userName";
static String DB_SUBSCRIPTION_EXPIRATION = "subscriptionExpiration";
static String DB_REMOTE_ACCESS_ENABLED = "remoteAccessEnabled";
static String DB_LOCAL_USERNAME = "root";
static String DB_LOCAL_PASS = "root";
public static void main(String[] args)
{
Timer timer = new Timer(2000, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent evt)
{
TestLeak tester = new TestLeak();
try
{
tester.go();
}
catch (NumberFormatException n)
{
}
tester = null;
}
});
timer.start();
while (true)
{
//keep the program from ending...
}
}
private void go() throws NumberFormatException
{
ResultSet results = null;
Connection conn = null;
Properties connectionProps = new Properties();
try
{
connectionProps.put("user", "root");
connectionProps.put("password", "root");
conn = DriverManager.getConnection("jdbc:mysql://localhost:8889/myDataBase",
connectionProps);
connectionProps = null;
try
{
String rawQuery = new String("SELECT " + TestLeak.DB_USERNAME + ", "
+ TestLeak.DB_REMOTE_ACCESS_ENABLED
+ ", " + TestLeak.DB_SUBSCRIPTION_EXPIRATION + " FROM myTable");
Statement statement = conn.createStatement();
try
{
statement.executeQuery(rawQuery);
results = statement.getResultSet();
rawQuery = null;
try
{
while (results.next())
{
String auth = new String(results.getString(TestLeak.DB_REMOTE_ACCESS_ENABLED));
if (auth.equals("1"))
{
Long subExpires = Long.valueOf(results.getString(TestLeak.DB_SUBSCRIPTION_EXPIRATION));
if (subExpires > System.currentTimeMillis())
{
System.out.println(results.getString(TestLeak.DB_USERNAME));
System.out.println();
}
subExpires = null;
}
auth = null;
}
}
finally
{
results.close();
}
}
finally
{
statement.close();
}
}
finally
{
conn.close();
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
}
我想我释放一切,但必须防止所有对象被释放。为什么go()方法结束时,所有对象都不符合垃圾回收的条件?每次我在分析器中启动垃圾回收时,我都会得到另一代幸存者。 谢谢。
所以......把它放在调试器中,弄清楚什么是错误的。 – 2012-04-02 21:14:41
SQLException catch块位于清理JDBC资源的finally块之外。你是否得到任何SQLExceptions?在附注中,有一些方法可以清理JDBC资源,而不必像这样嵌套try/catch/finally块,这会使代码更容易阅读。 – rfeak 2012-04-02 21:19:07
确保那些'.close'实际上被调用。另外,我认为那些“接近”的声明需要在他们自己的try-catch中进行,否则第一次失败会导致剩下的不执行?我相信你的情况下,你应该在'catch'下面有一个'finally'并且处理(你的'ResultSet','Statement'和'Connection')的清理。 – nevets1219 2012-04-02 21:19:45