Connection pooling allows you to reuse connections rather than create a new one every time the JDBC Client needs to establish a data access connection. Connection pooling manages connection sharing across different user requests to maintain performance and reduce the number of new connections that must be created. For example, compare the transaction sequences shown in Example A: Without Connection Pooling and Example B: With Connection Pooling .
Example A: Without Connection Pooling
1. The client application creates a connection.
2. The client application sends a data access query.
3. The client application obtains the result set of the query.
4. The client application displays the result set to the end user.
5. The client application ends the connection.
Example B: With Connection Pooling
1. The client checks the connection pool for an unused connection.
2. If an unused connection exists, it is returned by the pool implementation; otherwise, it creates a new connection.
3. The client application sends a data access query.
4. The client application obtains the result set of the query.
5. The client application displays the result set to the end user.
6. The client application returns the connection to the pool.
Note: The client application still calls close(), but the connection remains open and the pool is notified of the close request.
The pool implementation creates real database connections using the getPooledConnection() method of ConnectionPoolDataSource. Then, the pool implementation registers itself as a listener to the PooledConnection. When a client application requests a connection, the pool implementation is notified by the ConnectionEventListener interface that the connection is free and available for reuse. The pool implementation is also notified by the ConnectionEventListener interface when the client somehow corrupts the database connection, so that the pool implementation can remove that connection from the pool.
Once a JDBC data source has been registered with JNDI, it can be used by your JDBC application as shown in the following example, typically through a third-party connection pool tool:
In this example, the JNDI environment is first initialized. Next, the initial naming context is used to find the logical name of the JDBC data source. The Context.lookup() method returns a reference to a Java object, which is narrowed to a javax.sql.ConnectionPoolDataSource object. Finally, the ConnectionPoolDataSource.getPooledConnection() method is called to establish a connection with the service.