Video in progress
After a few hours this JDBC code starts throwing "Connection is not available, request timed out". What is the problem?
public Optional<String> findEmail(long id) throws SQLException {
Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT email FROM users WHERE id = ?");
ps.setLong(1, id);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
return Optional.empty();
}
String email = rs.getString(1);
rs.close(); ps.close(); con.close();
return Optional.of(email);
}
When an error occurs or the ResultSet is empty, close() is never called and the connection doesn't go back to the pool: a connection leak. Over time every connection in the pool is left "hanging". The fix is try-with-resources.
📖 Answer
There are two holes here: if the user isn't found, return Optional.empty() closes nothing; and if executeQuery or getString throws an exception, nothing is closed either. Every such call "steals" one connection from the pool forever. With a pool of 10, the application stops after 10 ids that aren't found.
The correct version:
public Optional<String> findEmail(long id) throws SQLException {
String sql = "SELECT email FROM users WHERE id = ?";
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setLong(1, id);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? Optional.of(rs.getString(1)) : Optional.empty();
}
}
}
Resources are closed in reverse order, whatever happens.
To find a leak on prod, HikariCP has leakDetectionThreshold:
spring.datasource.hikari.leak-detection-threshold: 20000 # 20 s
If a connection isn't returned within that time, the stack trace of the place that took it is written to the log. If you use Spring's JdbcTemplate or JPA, this problem almost disappears, because they manage the connection themselves.
Sign up to mark studied questions and save your progress.