Since you tagged SQL as well, I strongly suspect that your webapp is leaking SQL connections. I.e., your webapp is getting a connection and keeping it open all the time and never closing it. Because the connection is been too long open, the DB will force a timeout and close of the connection after a certain period. E.g. MySQL will do that after 8 hours. Reloading the webapp will cause a new connection been acquired and hold. But this doesn't fix the actual problem.
This issue is pretty common among new-to-webapp (and new-to-database) developers.
All you need to do is to rewrite your JDBC code so that it properly acquires and closes the Connection
(and Statement
and ResultSet
) in the shortest possible scope. You also need to use a finally
block to ensure the close for the case an exception is been thrown. Here's a kickoff example:
public List<Entity> list() throws SQLException {
// Declare resources before try.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Entity> entities = new ArrayList<Data>();
try {
// Acquire resources and query DB in try.
connection = database.getConnection();
statement = connection.createStatement("SELECT id, name, value FROM entity");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setName(resultSet.getString("name"));
entity.setValue(resultSet.getInteger("value"));
entities.add(entity);
}
} finally {
// Close resources in reversed order in finally.
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
// Return result.
return entities;
}
If you want to improve connecting performance, then you should consider using a Connection Pool instead of keeping the connection all the time open.
See also: