gpt4 book ai didi

java - 噩梦 java 泄漏......带有循环和 jdbc

转载 作者:行者123 更新时间:2023-11-29 01:31:47 28 4
gpt4 key购买 nike

当我在探查器中运行以下代码时,我得到一个 char[] 和 byte[],它们会不断累积,直到程序因 Java 堆内存不足异常而崩溃。有人能告诉我为什么吗?也许我在做一些根本性的错误。

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() 方法结束时所有对象都不符合垃圾回收条件?每次我在探查器中调用垃圾收集时,我都会得到另一个幸存的一代。谢谢。

最佳答案

我会改变这个:

                        statement.executeQuery(rawQuery);
results = statement.getResultSet();

为此:

                        results = statement.executeQuery(rawQuery);

后者肯定是 API 批准的执行此操作的方法,虽然我不能肯定地说前者是一个问题,但它确实似乎可以创建两个单独的结果-集合,其中你只能关闭一个。

关于java - 噩梦 java 泄漏......带有循环和 jdbc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9983880/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com