Connection pooling means a pool of Connection Objects. Connection pooling is based on an object pool design pattern. Object pooling design pattern is used when the cost (time & resources like CPU, Network, and IO) of creating new objects is higher. As per the Object pooling design pattern, the application creates an object in advance and place them in Pool or Container. Whenever our application requires such objects, it acquires them from the pool rather than creating a new one.
An application that uses a connection pooling strategy has already DB connection objects which can be reused. So, when there is a need to interact with the database, the application obtains connection instances from Pool. Connection pooling improves application performance that interacts with the database.
Connection Pooling
We can create our own implementations of Connection pooling. Any connection pooling framework needs to do three tasks.
Creating Connection Objects
Manage usage of created Objects and validate them
Release/Destroy Objects
With Java, we have great set of libraries which are readily available. We only need to configure few properties to use them.
Let’s have a look at below examples of them one by one. For demo purpose we will use MySQL database and Eclipse IDE. We will also create simple Java Project based on maven using JDK 1.8.
HikariCP is fast, reliable, and simple. It is one of the preferred solutions for Connection Pooling. Frameworks like Spring Boot 2.x uses it as a default connection manager.
To use HikariCP, add following dependency in pom.xml of our project.
We can use Java based configuration as shown in our below example program or we can use property file to configure HikariCP. Let’s have a look at below properties.
idleTimeout: Time in milliseconds for which connection object can stay in the pool as idle. It works with minimumIdle and maximumPoolSize properties. After a specified time connection object will be released.
connectionTimeout: Time in milliseconds for which the client will wait for connection object from Pool. If the time limit is reached then SQL Exception will be thrown.
autoCommit: We can specify true or false and if it is set to true then it will automatically commit every SQL statements you execute and if it is set to false then we need to commit SQL statements manually
cachePrepStmts: Enable caching for Prepare Statement
minimumIdle: Minimum number of connection objects needs to remain in the pool at any time.
maximumPoolSize: Maximum number of connections that can stay in the pool.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.