Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new connections and retrieve them later in HikariCP

Tags:

java

hikaricp

Would anyone care to elaborate how the HikariCP handles connections in the pool? How do you put a new connection in the pool, and how can you call on it / retrieve it later?

This is my current code:

    HikariConfig config = new HikariConfig();
    config.setMaximumPoolSize(100);

    config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    config.addDataSourceProperty("serverName", "localhost");
    config.addDataSourceProperty("port", "8889");
    config.addDataSourceProperty("databaseName", "XXX");
    config.addDataSourceProperty("user", "XXX");
    config.addDataSourceProperty("password", "XXX");

    System.out.print("qq");

    HikariDataSource ds = new HikariDataSource(config);
    ds.setConnectionTimeout(800);
like image 832
miniHessel Avatar asked Oct 06 '14 19:10

miniHessel


1 Answers

With a pool, you don't add a connection to the pool to retrieve it later. You do the exact inverse: you get a connection from the pool when you need one, and close the connection when you're done with it to give it back to the pool. The HikariDataSource, as its name indicates, is a DataSource. A DataSource is an object from which you get connections.

The pool handles the opening of the connection for you. It puts you in a waiting queue if no connections are available automatically, etc.

Depending on the properties of the pool, the pool can open the connections immediately or on demand, keep a given number of connections always opened, shrink the pool size after given amount of unused time, etc.

That's all very well documented: https://github.com/brettwooldridge/HikariCP#user-content-configuration-knobs-baby

Example code (Java 7 and later):

try (Connection connection = ds.getConnection()) {
    // use the connection
}

Example code (Before Java 7):

Connection connection = ds.getConnection();
try {
    // use the connection
}
finally {
    connection.close();
}
like image 51
JB Nizet Avatar answered Sep 27 '22 21:09

JB Nizet