Lab 6: Setting up the connection pool

Video lesson published on

This page was originally written in Portuguese. Read the original.

Lab overview and objectives

This lab aims to present a basic way to set up a connection pool to manage the database connections!

A connection pool is a technique used to improve the performance of applications that frequently use database connections.

After completing this lab, you should be able to:

This lab is also available as a video lesson on YouTube

Car Store #08 - Implementando um Connection Pool com Apache Commons DBCP · Video in Portuguese.

Task 1: Adding the Apache Commons DBCP dependency

1 - Adding the dependency

In IntelliJ IDEA, open the project configuration file called “pom.xml” (usually located in the project root).

Find the <dependencies> section and add the following dependency:


<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.9.0</version>
</dependency>

NOTE: No code should be removed in this step. Just add the new dependency to the pom.xml.

2 - Save all changes (CTRL + S)

NOTE: After you save the changes, IntelliJ IDEA should automatically sync the configuration file changes and download the Apache Commons DBCP library.

Task 2: Creating the Connection Pool class

1 - Create a configuration class for the connection pool

In IntelliJ IDEA, go to the main package br.com.carstore, right-click it, select New / Package, type config and press ENTER. The config package must be at the same level as the dao, model and servlet packages (br.com.carstore.config).

Once the config package is created, right-click the config package and select New / Java Class.

Set the class name to “ConnectionPoolConfig” and click “OK”.

2 - Open the class we have just created and implement a static method called getDataSource that receives no parameters and returns a BasicDataSource, as in the following code:


import org.apache.commons.dbcp2.BasicDataSource;

public class ConnectionPoolConfig {

    private static BasicDataSource dataSource;

    private static BasicDataSource getDataSource() {

    }

}

At this point, IntelliJ will report an error because the method has no return statement yet. Don’t worry, this will be fixed in the next step.

NOTE: Don’t forget to import the BasicDataSource class from the org.apache.commons.dbcp2 package. To import it with IntelliJ, place the cursor on the class name, use the (ALT + ENTER) shortcut and select import class.

3 - Now that our BasicDataSource class and our getDataSource() method are created, let’s start the implementation. The first part is a conditional check that verifies whether the dataSource variable is null.

The resulting code should look like the following:


package br.com.carstore.config;

import org.apache.commons.dbcp2.BasicDataSource;

public class ConnectionPoolConfig {

    private static BasicDataSource dataSource;

    private static BasicDataSource getDataSource() {

        if (dataSource == null) {

        }

        return dataSource;

    }

}

If this conditional check is true, we will create a new dataSource (shown in the next section). If it is false, a dataSource already exists, so we return it without doing anything else.

4 - Assuming the conditional check returned true, we need to create a new dataSource. To do so, we will create a new instance of BasicDataSource and pass some parameters:

  • URL
  • Username
  • Password
  • Min Idle
  • Max Idle
  • Max total

Notice that we already used some of these parameters in the previous implementations (url, username and password). But now we are adding three new parameters (Min Idle, Max Idle and Max total).

These parameters are needed to configure our pool, and they may vary according to the characteristics of your application.

Here is a short description of what these parameters do:

  • MinIdle: Minimum number of idle connections in the pool
  • MaxIdle: Maximum number of idle connections in the pool
  • MaxTotal: Maximum number of total connections in the pool

Finally, let’s add a feedback message for our users, signaling that a new connection pool was created successfully.

The resulting code should look like the following:

package br.com.carstore.config;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionPoolConfig {

    private static BasicDataSource dataSource;

    private static BasicDataSource getDataSource() {

        if (dataSource == null) {
            dataSource = new BasicDataSource();
            dataSource.setUrl("jdbc:h2:~/test");
            dataSource.setUsername("sa");
            dataSource.setPassword("sa");
            dataSource.setMinIdle(5);   // Minimum number of idle connections in the pool
            dataSource.setMaxIdle(10);  // Maximum number of idle connections in the pool
            dataSource.setMaxTotal(50); // Maximum number of total connections in the pool

            System.out.println("New connection pool created with successful");

        }

        return dataSource;

    }

}

5 - Creating the getConnection method

Now that the getDataSource method is implemented, we need to create the method that hands out connections to the callers.

To do so, let’s create a new static method called getConnection that returns a connection.

The resulting code should look like the following:

public static Connection getConnection() throws SQLException {

    return getDataSource().getConnection();

}

6 - Creating a private constructor

Now that the getDataSource() and getConnection() methods are created, we need a private constructor that calls the getDataSource method to start a new connection pool as soon as our class is called for the first time.

The resulting code should look like the following:

private ConnectionPoolConfig() {
    getDataSource();
}

With everything implemented, the code of the ConnectionPoolConfig class should look like the following:

package br.com.carstore.config;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionPoolConfig {

    private static BasicDataSource dataSource;

    private ConnectionPoolConfig() {
        getDataSource();
    }

    private static BasicDataSource getDataSource() {

        if (dataSource == null) {
            dataSource = new BasicDataSource();
            dataSource.setUrl("jdbc:h2:~/test");
            dataSource.setUsername("sa");
            dataSource.setPassword("sa");
            dataSource.setMinIdle(5);   // Minimum number of idle connections in the pool
            dataSource.setMaxIdle(10);  // Maximum number of idle connections in the pool
            dataSource.setMaxTotal(50); // Maximum number of total connections in the pool

            System.out.println("New connection pool created with successful");

        }

        return dataSource;

    }

    public static Connection getConnection() throws SQLException {

        return getDataSource().getConnection();

    }

}

Save all changes (CTRL + S)

Task 3: Refactoring the DAO class to use the connection pool

1 - Now that our connection pool is created and configured, it is time to refactor the CarDao class so that it uses the connections provided by our connection pool.

To do so, in IntelliJ IDEA, go to the br.com.carstore.dao package and double-click CarDao to open it.

With the CarDao class open, we can start our refactoring.

2 - The CarDao class has several methods:

  • createCar()
  • findAllCars()
  • deleteCarById()
  • updateCar()

All of them open a new connection to the database, which is not a good practice.

NOTE: This was done on purpose.

Now, with our connection pool in place, no DAO method will create connections anymore. Instead, it will ask our pool for a connection, and the pool will reuse the existing connections that are available or, if there are none, create a new connection.

This way, we save computing resources and, as a result, our application performs better.

Inside each method listed above, find the line that opens the connection and replace it:

REMOVE:

Connection connection = DriverManager.getConnection("jdbc:h2:~/test", "sa","sa");

System.out.println("success in database connection");

ADD:

Connection connection = ConnectionPoolConfig.getConnection();

NOTE: Don’t forget to import the ConnectionPoolConfig class in the CarDao class (use the ALT + ENTER shortcut). The resulting import should look like the following:

import br.com.carstore.config.ConnectionPoolConfig;

Now the methods no longer open connections directly and therefore will not write the message (“success in database connection”), because opening new connections is now the responsibility of our BasicDataSource class.

Here we are applying the S of SOLID.

3 - Review everything you have done so far!

4 - Save all changes (CTRL + S) and run your application (tomcat7:run).

Open your application at http://localhost:8080 and register a car. Notice that the application behaves the same, but the message (“New connection pool created with successful”) is written only once to stdout. This is the expected behavior, because our application now reuses the connections that are already open and available whenever possible, and all of this is managed by our connection pool.


Congratulations! 👍

You added a connection pool to your application with the Apache Commons DBCP library, and now your application manages the database connections efficiently.