Open In App

How to Implement Connection Timeout with HikariCP in JDBC?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

HikariCP is a lightweight, high-performance JDBC connection pooling library that provides fast and efficient management of database connections for Java applications. In this article, we are going to implement a connection timeout with HikariCP.

HikariCP Library

Let’s ensure that we have the HikariCP library added to our Java project’s dependencies.

For Maven:

<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.0.1</version>
</dependency>

For Gradle:

implementation group: 'com.zaxxer', name: 'HikariCP', version: '5.0.1'

Database Driver

We need the JDBC driver for the specific database management system. In this example, we are going to use the MySQL database. So, for the MySQL database, we will need the MySQL JDBC driver. We have to ensure that the JDBC driver JAR file is included in our project’s dependencies.

Follow this Link to Download the MySQL JDBC Driver.

Connection Timeout Implementation with HikariCP in JDBC

Setting a connection timeout with HikariCP is important to prevent application hang-ups and ensure a smooth user experience. Without it, our application might take long time when facing database issues.

We can implement multiple connection pool properties as per our project requirement to swiftly identify and handle connectivity issues, ensuring it remains responsive and reliable.

In this example, we have implemented few frequently used connection pool properties, for different requirements we can use these dedicated properties in our project.

Java




import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
  
import java.sql.Connection;
import java.sql.SQLException;
  
public class Main {
    public static void main(String args[]) 
    {
        /**  HikariCP configuration
         *  update it with your actual database URL, username, and password
         *   JdbcUrl :  "jdbc:mysql://localhost:3306/mydb"
         *   username: yourusername
         *   password : yourpassword
         */
  
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
        config.setUsername("iamuser");
        config.setPassword("abcismypass");
  
        // Connection pool properties
        config.setConnectionTimeout(20000); // 20 seconds in milliseconds
        config.setMaximumPoolSize(10);  // Maximum number of connections in the pool
        config.setMinimumIdle(5);        // Minimum number of idle connections in the pool
        config.setIdleTimeout(60000);      // Maximum time a connection can remain idle in the pool (60 seconds)
        config.setMaxLifetime(1800000);     // Maximum lifetime of a connection in the pool (30 minutes)
        config.setKeepaliveTime(600000);    // Keepalive time in milliseconds (10 minutes)
        config.setConnectionTestQuery("SELECT 1"); // Connection test query
        config.setPoolName("MyPool");       // Pool name
        config.setIdleTimeout(300000); // 5 minutes
  
        HikariDataSource dataSource = new HikariDataSource(config);
  
        // Creating connection with the pool
        try (Connection connection = dataSource.getConnection()) 
        {
            System.out.println("Connected to database!");
  
        } catch (SQLException e) {
            // In case of failed Connection
            e.printStackTrace();
        } finally {
            // Close the DataSource when done
            dataSource.close();
        }
    }
}


Configuration for HikariCP

We can also use these properties to optimize database connectivity and query performance by caching prepared statements, utilizing server-side resources efficiently, and enabling features like rewriting batched statements.

jdbcUrl=jdbc:mysql://localhost:3306/mydb
username=abc
password=xyz
dataSource.cachePrepStmts=true
dataSource.prepStmtCacheSize=350
dataSource.prepStmtCacheSqlLimit=2048
dataSource.useServerPrepStmts=true
dataSource.useLocalSessionState=true
dataSource.rewriteBatchedStatements=true
dataSource.cacheResultSetMetadata=true
dataSource.cacheServerConfiguration=true
dataSource.elideSetAutoCommits=true
dataSource.maintainTimeStats=false

Output:

After successful connection with Database and HikariCP configuration, the expected output will be something like this:

Output in Console after Connection Timeout



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads