JDBC memory leaks
Posted by: Tyler Blair
Date: July 25, 2009 10:14AM

Hi everyone,

I seem to be having a problem with JDBC.. It leaks memory after some time. My application connects to MySQL to verify user accounts, uses it for logs, everything..

After a few hours, memory jogs up to 500mb+, and the evil user is:

com.mysql.jdbc.JDBC4Connection -> Shallow Heap [ 1,088 ] Retained Heap [ 495,884,816] Percentage [ 90,03% ]


For my ResultSets, I close them after, and close the statement as well. for querying I use PreparedStatements, in which I clear it and close it afterwards..



Example insertion using PreparedStatements: (for simplicity sakes, only one value)
		try {
			final PreparedStatement p = con
					.prepareStatement("INSERT INTO `chat_logs` SET `message` = ?");
			p.setString(1, "message");
			p.executeUpdate();
			p.clearParameters();
			p.close();
		} catch (final SQLException e) {
			System.err.println("MySQLException: " + e.getMessage());
		}

However, I've iterated that thousands upon thousands of times with static values. Memory usage goes up slightly and goes back down when the queries are done. As expected.



Querying:
		String temp = "";
		try {
			final ResultSet rs = executeQuery("SElECT `message` FROM `news` ORDER BY `id` ASC");
			while (rs.next()) {
				temp += rs.getString("message") + "\\n";
			}
			rs.close();
			stmt.close();
		} catch (final SQLException e) {
			e.printStackTrace();
		}
		return temp;
However, with this piece of code, the leak would happen WITHOUT the stmt.close(), when I added that, it no longer happened in the controlled scenario.


Connecting:
        final String username = "";
        final String password = "";
        final String host = "localhost";
	public boolean connect() {
		con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			Properties prop = new Properties();
			prop.put("user", username);
			prop.put("password", password);
			prop.put("autoreconnect", "true");
			con = DriverManager.getConnection("jdbc:mysql://" + host + "/"
					+ database, prop);
			if (!con.isClosed()) {
				return true;
			}
		} catch (final Exception e) {
		}
		return false;
	}

The leak also happened before I began using properties for connecting, so I don't think it's that somehow.



So.. If you see something that's out of place, that is probably it, thanks very much.

Options: ReplyQuote


Subject
Written By
Posted
JDBC memory leaks
July 25, 2009 10:14AM
July 25, 2009 10:40AM
August 25, 2009 12:42PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.