Programmatically restart HikariPool in Spring Boot application?

Tags: , , , ,

I have a Spring Boot application which uses Hibernate, and HikariDataSource / HikariPool to talk to the database.

A special feature in the app triggers database restart. Currently this breaks the connections in HikariPool:

Caused by: org.postgresql.util.PSQLException: ERROR: relation "relation_which_really_exists" does not exist
Position: 113
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(
at org.postgresql.core.v3.QueryExecutorImpl.processResults(
at org.postgresql.core.v3.QueryExecutorImpl.execute(
at org.postgresql.jdbc.PgStatement.executeInternal(
at org.postgresql.jdbc.PgStatement.execute(

Old version of the app does call programmatically org.hibernate.SessionFactory.close(); which causes restart of HikariDataSource / HikariCP:

2020-08-17T11:36:42.628Z [qtp1340328248-76] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
2020-08-17T11:36:42.698Z [qtp1340328248-76] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.
2020-08-17T11:36:51.266Z [qtp1340328248-12] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Starting...
2020-08-17T11:36:51.515Z [qtp1340328248-12] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-2 - Start completed.

I would like to do the same, but how can I programmatically restart the connection pool in my app? I’ve seen things like Spring Boot – Handle to Hibernate SessionFactory to get a handle to sessionFactory, and maybe something similar to get a handle to DataSource or CP….but is it OK to close / restart those objects violently, is the Spring Boot context designer to handle such action properly?

There’s probably some HikariCP configuration parameters that I can start to experiment with to try reach the same end result, but replicating the old implementation tempts as the easiest / most figured out and most probable to reach same end result.


After some study, found out that you can get handle of HikariCP and trigger connection eviction by:

    HikariDataSource hikariDs = (HikariDataSource) dataSource;
    HikariPoolMXBean poolBean = hikariDs.getHikariPoolMXBean();

Source: stackoverflow