man_rocks
man_rocks

Reputation: 65

Why HikariCP creates new connection for every web app in Tomcat on startup

When I define HikariCP with Tomcat 7 as JNDI inside context.xml like the below, every time I deploy new web application, it opens new connections to mysql server. For example, if I have 5 Apps in Tomcat, it will open 50 connections, 10 for each App. However, in C3p0, using the same settings and the same tomcat instance, it only creates a pool with 10 connections and share this pool with All Apps. I mean, in C3P0, the pool doesn't open new connection per APP while in HikariCP, it does. Was this done for a reason and is there anyway to change it?

<Resource name="jdbc/testDatasource" 
      auth="Container" 
      factory="com.zaxxer.hikari.HikariJNDIFactory" 
      type="javax.sql.DataSource" 
      driverClassName="com.mysql.jdbc.Driver"
      jdbcUrl="jdbc:mysql://localhost:3306/football" 
      username="xxx" 
      password="xxx" 
      minimumIdle="3" maximumPoolSize="10" connectionTimeout="300000" maxLifetime="1800000" />

Upvotes: 3

Views: 2472

Answers (1)

Aboodz
Aboodz

Reputation: 1594

As documented, tomcat loads the configuration in context.xml for each web application in the container. When you have 5 web application, HikariCP will be loaded for each application (5 times). So this behavior is normal with anything configured in context.xml file.

If you want HikariCP to load only once and regardless of the number of applications in the container, you need to define HikariCP JNDI in server.xml file not context.xml. This goes as the follwing:

Define HikariCP JNDI in server.xml:

<GlobalNamingResources>
      <Resource name="jdbc/testDatasource" 
      auth="Container" 
      factory="com.zaxxer.hikari.HikariJNDIFactory" 
      type="javax.sql.DataSource" 
      driverClassName="com.mysql.jdbc.Driver"
      jdbcUrl="jdbc:mysql://localhost:3306/football" 
      username="xxx" 
      password="xxx" 
      minimumIdle="3" maximumPoolSize="10" connectionTimeout="300000" maxLifetime="1800000" />
</GlobalNamingResources>

Reference the JNDI resource in context.xml:

<Context>
   <ResourceLink name="jdbc/testDatasource"
            global="jdbc/testDatasource"
            type="javax.sql.DataSource" />
</Context>

Note: Using this setting will require restarting the web server each time you want to reload HikariCP setting. Redeploying the application will no longer result in reloading the HikariCP.

Upvotes: 5

Related Questions