DBCP has an option to request connection validationQuery - validationQuery , according to the docs . You can set it to something like SELECT 1; , and DBCP will run this before returning the connection to verify it.
However, your application really needs to handle this case. SQL queries can fail for various reasons, and you should always run your queries in a retry loop with time and retry limits, as well as some logic to decide which exceptions can be recovered by retrying and which are not (use SQLState to of this).
In particular, validation is subject to a race condition where you can have an order of events, for example:
- Validate
- Skip connection to application
- Server shutdown
- The application launches the first statement
or
- Validate
- Skip connection to application
- The application launches the first statement, opening a transaction
- Server shutdown
- Application launches second statement
... therefore, it is important that your application has the correct retry cycle and good transaction processing.
You can get SQLState from SQLException: SQLException.getSQLState . Codes for PostgreSQL in the PostgreSQL manual .
source share