Connection Pooling in Java With Examples

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

ConnectionPooling

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.

Connection Pooling in Java Application

Let’s have a look at below libraries:

  • Apache Commons DBCP 2
  • HikariCP
  • C3P0

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.

Database Scripts

Example Project

Follow below steps to create new project.

1) Open Eclipse IDE.

2) Click File menu and select new -> Maven Project

3) The below screen will be displayed. Select create a simple Project option and click the Next Button.

New Maven Project

NewMavenProject

4) Enter any Group Id, Artifact Id, Name and description.

Maven Project ConfigsMaven Project Configs

MavenProjectConfigs

Click Finish Button.

5) Add following dependency in your pom.xml for MySQL.

6)  Right-click on Project, select Maven -> Update Project -> Ok. It will download all the dependencies.

1) Apache commons DBCP 2

DBCP is from Apache Common Project. DBCP 2.7 requires Java 8. To use DBCP 2, you need to add following dependency in your project.

Apache DBCP 2.0 provides two types of DataSource (BasicDataSource and PoolingDataSource).

BasicDataSource: As the name suggests, it is simple and suitable for most common use cases. It internally creates PoolingDataSource for us.

Let’s have a look at below steps to initialize connection pool.

  1. Create an instance of  BasicDataSource
  2. Specify JDBC Url, database username and password
  3. Specify the minimum number of idle connection ( Minimum number of connections that needs to remain in the pool at any time)
  4. Specify the maximum number of idle connection (Maximum number of Idle connection in the pool)
  5. Specify the total number of maximum connections.

Output:

PoolingDataSource: It offers more flexibility. You only need to change code which creates DataSource. The rest of the code will remain the same.

Let’s have a look at below steps to initialize connection pool:

  1. Create an instance of ConnectionFactory using JDBC URL.
  2. Create an instance of  PoolableConnectionFactory using an instance of  ConnectionFactory which was created in step 1
  3. Create an instance of  GenericObjectPoolConfig and set maximum idle, minimum idle and maximum connection properties
  4. Now initialize  ObjectPool using instances created in step 2 and step 3
  5. Now set pool as an instance of  PoolableConnectionFactory
  6. Finally, initialize an instance of  DataSource

2) HikariCP

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.

HikariCP Configuration:

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.

Output:

3) C3P0

C3P0 is one of oldest library. Generally, it is used with Hibernate. To use C3P0, we need to add following dependency to project.

We can configure following properties with C3P0.

  • driverClass: Preferred Jdbc Driver
  • jdbcUrl: JDBC Url for the database.
  • initialPoolSize: Number of connections created in the pool at startup.
  • acquireIncrement: Number of new connections needs to be created when the current size is not enough.
  • maxIdleTime: Number of seconds Connection can remain in Pool without being used.
  • maxPoolSize: Maximum number of connections that can stay in Pool.
  • minPoolSize: Minimum number of connection objects needs to remain in Pool at any time.

Output:

That’s all for the JDBC Connection pool example tutorial, I hope nothing important got missed here.

ReferencesHikariCP, Apache Commons DBCP, C3P0

By admin

Leave a Reply

%d bloggers like this: