How to Implement Connection Timeout with HikariCP in JDBC?
Last Updated :
28 Apr, 2025
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:
-(1).png)
Similar Reads
How to Handle Connection Pooling in JDBC in Java? In Java applications, interacting with the databases using JDBC (Java Database Connectivity), and managing the database connections efficiently is crucial for optimal performance and resource utilization. Connection pooling is the technique employed to achieve the goal by reusing the established dat
5 min read
How to handle connection leaks in JDBC? In this article, we will learn how to handle connection leaks in JDBC. Handling connection leaks in JDBC involves ensuring that database connections are properly closed after they are no longer needed. The connection leaks occur when a connection is opened but not closed. Due to connection leaks, th
4 min read
How to Handle Timeouts in Network Communication in Java? In Java, Timeouts in Network Communication mean when the end user sends a request to the server through a network, the server takes a lot of time to process the request and send it the in form of a response. In real-time applications we need to handle this situation for end users we need to give one
4 min read
How to Connect to a Database Using JDBC with SSL/TLS? Connecting to a database using JDBC with SSL/TLS is nothing but it will Setup a secure connection between the Java program(from IDE, for Example: Eclipse) and the database server, and it will ensure that transferring the data between the Java program and database server is protected. Connecting to t
3 min read
How to Execute a SQL Query with Pagination in JDBC? To execute a SQL query with pagination in JDBC (Java Database Connectivity), normally we use SQL syntax to limit the number of rows returned and then iterate through the results as per the need. We often use SQL's LIMIT and OFFSET clauses to execute page SQL queries in JDBC. Steps to Execute SQL Que
3 min read
How to Implement a Simple JDBC Logging Mechanism? JDBC stands for Java Database Connectivity. Implementing the simple JDBC logging mechanism involved the statements of the logging into the JDBC code. It is used for the flow of execution, errors in the code, and other related information. The logging mechanism allows us to record valuable data durin
3 min read