DBCP has a connection validation query option - validationQuery
, according to the docs. You can set it to something like SELECT 1;
and DBCP will run that before returning a connection to test it.
That said, your app really should handle this case. SQL queries can fail for all sorts of reasons and you should always do your queries in a retry loop with a time back-off and retry limit, plus some logic to decide what exceptions are recoverable on retry and which aren't (use the SQLState for that).
In particular, validation is subject to a race condition where you can have event orderings like:
- Validate
- Pass connection to app
- Server shutdown
- App runs first statement
or
- Validate
- Pass connection to app
- App runs first statement, opening a transaction
- Server shutdown
- App runs second statement
... so it remains important for your app to have a proper retry loop and good transaction handling.
You can get the SQLState from the SQLException: SQLException.getSQLState
. The codes for PostgreSQL are in the PostgreSQL manual.