21

I am trying to use HikariCP connection pool. I was able to get it to work and get a connection that I could use. I am not sure what is the best approach for returning the connection to the pool.

I have the following questions:

  • Should I close the connection when I am done, rely on idleTimeout and maxLifetime settings or is there another call that I can use so as not to hog the connections from the pool?
  • If I close the connections (instead of returning to the pool), would that not result in additional connection objects being created to meet the requirements of the connection pool size?

Looking for helpful suggestions.

informatik01
  • 15,174
  • 9
  • 67
  • 100
  • 4
    Not sure about Hikari, but in most connection pools, what you get is not the actual connection, but rather a wrapper that has a different `close` method (apart from other things). Said close method actually returns the connection to the pool rather than closes it. – Ordous Aug 18 '14 at 15:53

1 Answers1

59

As with most connection pools, Hikari doesn't give you an actual JDBC Connection when you ask for one. What it does instead is give you a proxy that implements the Connection interface. In the case of Hikari - it's a ConnectionProxy object.

This proxy serves a few purposes, the main of which is - take the control of opening/closing connections and statements away from you and into the connection pool. This happens automagically and you should be using your connections as usual. This includes closing them after use.

If you look at the source code for Hikari, at the ConnectionProxy class in particular, you will see that the close() method is very different from the standard one. The code reads as:

Mark the connection as closed, do cleanup, reset underlying connection state and params.

Hence, simply calling close() will just clean and return the connection to the pool.

Ordous
  • 3,648
  • 13
  • 25
  • Yea I was confused about this as well but having stepped through their source-code I can confirm that simply calling .close() is all you need to do to safely return the connection to the pool. – Albert Rannetsperger Aug 12 '16 at 11:14
  • If i close the dataSource rather closing the connection by calling shutdown() what will the impact of that? – Irfan Nasim Jul 17 '18 at 12:43
  • 1
    @IrfanNasim If you close the `dataSource`, it will shutdown the entire pool, along with any active or inactive connections associated with it. – Ordous Jul 17 '18 at 12:56
  • @IrfanNasim I can only concur with the comments already there - the question is trivially answerable by reading the docs. It also has little to do with either this question or my answer to it. – Ordous Jul 17 '18 at 13:18