Programming is interesting!
Here's a bit of problem solving to do with coding practices, #PostgreSQL (or perhaps any database) and #Java.
Some customers (or at least their alerts) have been now and again reporting being unable to open a database connection as the available connections had run out. There's a lot of db activity, but I'd set the limits relatively high so was surprised.
However waking up this morning I had an idea (first tip - sleep on it!)
It might be that in some cases when an exception is raised, the transaction isn't rolled back before being closed. Take a method like this
```
public int getSomething() throws SomeException {
int something;
Connection conn = null;
try {
conn = Util.getConnection(); // Gets a connection and sets auto-commit to false
something = // do some work
conn.commit();
} catch (SQLException | OtherException ex) {
try {
conn.rollback();
} catch (SQLException sqlex) {
// Log error
}
// Handle exception
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException sqlex) {
// Log error
}
}
}
return something;
}
```
That's a typical sort of pattern for our code. It looks like everything's handled. What happens though if SomeException is thrown, as per the method signature? It could have been thrown in the 'do some work' bit. Now in that case, the connection will be closed in the finally block but the transaction won't have been committed or rolled back.
(1 of 2 or 3...)
@okohll I'd highly recommend using the try with resources syntax, it makes a lot of this much less error prone and cleaner.
Especially when using a pooler, calling close on the connection can leave the connection idle in a transaction.
Often it's worth just issuing the rollback and back to autocommit in a finally, small trade off for simplicity.
I tend to use a wrapper class which does the lower level connection management. Where auto close will issue a rollback and release the connection.
@intrbiz I would by preference use try with resources and skip the finally (generally do for prepared statements), but I don’t think the official Postgres JDBC driver does do rollback before close. I could be wrong - if there are any docs which say otherwise, they’d be good to see.