In this post, I am going to talk briefly about what JDBC connection pooling is and why it is important to use this technique in the DB driven applications.
A typical JDBC connection revolves around following aspects -
- open a connection to the database by using the corresponding JDBC driver
- open a TCP socket to read and write data over the socket
- close the socket
- close the connection
As can be deduced from the above aspects, creation of a JDBC connection is pretty time expensive operation. Generally speaking, the application shouldn't spend much time on JDBC connection creation while performing an operation involving DB interaction as it would add to the latency. Until unless, it becomes very much needed, JDBC connection creation for each and every DB operation should be avoided for the sake of having a faster application. The alternative to this is to have a pool of readily available JDBC connections in the application runtime. Whenever the application needs a DB connection, it can get one from the pool and if all the pooled connections have been used, then a new connection can be created. Once the DB operation is done, the connection can be returned to the pool.
There are several JDBC connection pooling implementation available to choose from. Some of the mostly used libraries are -
- Apache Commons DBCP
- HikariCP
- C3PO
These libraries support various features like maintaining minimum and maximum number of idle connections, connection timeout settings, prepared statement caching, maximum ResultSet size etc (all of these may not be supported by a single library).
Whenever a JDBC connection is used, it's important to close the Connection object along with ResultSet (if used) and Statement/PreparedStatement objects. This means that a Connection object retrieved from a JDBC connection pool also needs to be closed once the DB operation is done. But the catch is that the Connection object goes back to the pool instead of getting actually closed, the connection pooling libraries use wrappers to achieve that. Otherwise if the Connection object gets actually closed, it can't be reused and hence the whole point of connection pooling gets defeated. In the context of Spring, a Connection object gets automatically closed by either JDBC template or Spring managed transaction based on which one is used.
(Note: JDBC connections can be created using java.sql.DriverManager and javax.sql.DataSource classes. The former is DB agnostic whereas the latter is DB dependent.)
Comments