I have a method called QueryTest that queries a MySQL database over the network to get a table called output. From the start this method, when run, steadily keeps eating more memory until it eventually runs into an out of memory error. I have removed everything I can think of even putting the query in a loop with a 500ms time out but still no luck.
The program is meant to be run on a low memory device so I cannot have it continue increasing in memory usage.
Please see my code below. This class is called by another that only contains new Thread (new QueryTest ()).start () and has no other effect.
EDIT 1: If I add System.gc (); just before Thread.sleep it adds about 7mb to my program but the problem goes away. I know that method can only hint at the Garbage Collector so would this be a reliable workaround?
// 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);
}
}
}