0

So I am implementing connection pooling, with HikariCP. It seems simple enough, but I have some questions

I saw a tutorial and said that the code should look like this:

Connection connection = null;
try{
   connection = hikary.getConnection();
   ...
   ...
}catch(SQLException e){
  e.printStackTrace()
}finally{
  if(connection != null)
     connection.close(); // why?
}

So I know I'm probably asking a dumb question, but I don't understand what the point of pooling is, if you're closing the connection each time you get one?

Wouldn't that be the whole purpose of pooling connections? to recycle the connection?

Another question is that I'm assuming this hikari.getConnection() method is thread safe? I'm 99% sure it is but, I just go ahead and ask while I'm at it.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
centenond
  • 1,170
  • 1
  • 8
  • 23
  • You should really learn about [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html), it would simplify that code a lot. And please, restrict yourself to one question per question. – Mark Rotteveel Apr 01 '18 at 08:26
  • And regarding thread-safety a thing like a `DataSource`, and especially a data source providing a connection pool, is required to be thread-safe by the JDBC specification, but [here is an answer](https://stackoverflow.com/a/29744259/466862) by the creator of HikariCP that explicitly says it is thread-safe. – Mark Rotteveel Apr 01 '18 at 08:31
  • As @MarkRotteveel suggests, please use try-with-resources. If you do so consistently, you will avoid potential connection leaks that can be difficult to track down. – brettw Apr 02 '18 at 19:31

2 Answers2

2

Closing it doesn't really close: it returns it to the pool.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

Hikari wrapping close connection (and operation on connections) with its own mechanism of handling connection pool of active/idle connections as you setup by its properties.

Hikari getConnection has synchronized block

  // See http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
  HikariPool result = pool;
  if (result == null) {
     synchronized (this) {
Ori Marko
  • 56,308
  • 23
  • 131
  • 233