我有一个名为 QueryTest 的方法,它通过网络查询 MySQL 数据库以获取名为 output 的表。从一开始,这个方法在运行时会不断消耗更多的内存,直到最终遇到内存不足的错误。我已经删除了我能想到的所有内容,甚至将查询放入一个有 500 毫秒超时的循环中,但仍然没有运气。
该程序旨在在低内存设备上运行,因此我不能让它继续增加内存使用量。
请在下面查看我的代码。这个类被另一个只包含new Thread(new QueryTest()).start()的类调用,没有其他作用。
编辑1:如果我添加 System.gc (); 就在 Thread.sleep 之前,它为我的程序增加了大约 7mb,但问题消失了。我知道该方法只能暗示垃圾收集器,所以这是一个可靠的解决方法吗?
// Add the main package
package DBTest;
// Import List
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class QueryTest implements Runnable
{
// Constant Objects
public static Connection connection = null;
ResultSet rs;
ResultSetMetaData rsmd;
Statement s;
// Variables
int portA = 0;
int size = 0;
String outputs [][] = new String [0][5];
boolean isRunning = true;
boolean isPaused = false;
// The main method for starting the thread
public void run ()
{
// Try to connect to the database and query the updates
try
{
// Load the database driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Connect to the database
connection = DriverManager.getConnection ("jdbc:mysql://192.168.1.103/noah", "root", "0004e5dcb6a");
System.out.println ("Connection Made");
// let the loop run while the thread is allowed to run
while (isRunning)
{
// Query the database if the thread is not paused
if (!isPaused)
{
// Create a prepared statement
s = connection.createStatement ();
// Execute the query and store the results
rs = s.executeQuery ("SELECT * FROM outputs");
// Get the result set meta data
rsmd = rs.getMetaData();
// Set the result set to the last row
rs.last();
// Get the last row number
size = rs.getRow();
// Set the result set to the last row
rs.first();
/*// Get port A values
for (int a = 0; a < 8; a ++)
{
// Check if the output is active
if (Integer.parseInt(outputs [a][4]) == 1)
{
// Add to the port
portA = portA + Integer.parseInt (outputs [a][3]);
System.out.println (portA);
}
}*/
// Set the value of portA
portA = 0;
}
// Let the thread sleep
Thread.sleep (500);
}
// Close the connection
connection.close();
System.out.println ("Connection Closed");
}
// Catch a error
catch (Exception queryDatabaseErr)
{
System.out.println (queryDatabaseErr);
}
}
}