Search code examples
playframework-2.0hikaricp

Error on setting Hikari MetricRegistry


I am trying to use MetricRegistry for Hikary in a Play! application in Java as explained on Hikari's GitHub page. This is basically what I did:

 HikariDataSource dataSource = ((HikariDataSource) db.dataSource());
 dataSource.setMetricRegistry(metricRegistry);

But Hikari is complaining because the MetricRegistry shouldn't be set after construction. This is the error message I am getting:

java.lang.IllegalStateException: The configuration of the pool is sealed once started. Use HikariConfigMXBean for runti me changes.

Is there a better way to set this property, for example, by setting up the pool in the application config file?


Solution

  • You can use @PostConstruct for this purpose:

    @Configuration
    public class DataSourceConfiguration {
    
        private final MetricRegistry metricRegistry;
    
        private final DataSource dataSource;
    
        public DataSourceConfiguration(final MetricRegistry metricRegistry, final DataSource dataSource) {
            this.metricRegistry = metricRegistry;
            this.dataSource = dataSource;
        }
    
        @PostConstruct
        public void setUpHikariWithMetrics() {
            if (dataSource instanceof HikariDataSource) {
                ((HikariDataSource) dataSource).setMetricRegistry(metricRegistry);
            }
        }
    }