Package org.apache.tomcat.dbcp.dbcp2.datasources

package org.apache.tomcat.dbcp.dbcp2.datasources

This package contains two DataSources: PerUserPoolDataSource and SharedPoolDataSource which provide a database connection pool. Below are a couple of usage examples. One shows deployment into a JNDI system. The other is a simple example initializing the pool using standard Java code.


Most J2EE containers will provide some way of deploying resources into JNDI. The method will vary among containers, but once the resource is available via JNDI, the application can access the resource in a container independent manner. The following example shows deployment into tomcat (catalina).

In server.xml, the following would be added to the <Context> for your webapp:

  <Resource name="jdbc/bookstore" auth="Container"
   <ResourceParams name="jdbc/bookstore">

In web.xml. Note that elements must be given in the order of the dtd described in the servlet specification:

     Resource reference to a factory for java.sql.Connection
     instances that may be used for talking to a particular
     database that is configured in the server.xml file.

Apache Tomcat deploys all objects configured similarly to above within the java:comp/env namespace. So the JNDI path given for the dataSourceName parameter is valid for a ConnectionPoolDataSource that is deployed as given in the cpdsadapter example

The DataSource is now available to the application as shown below:

     Context ctx = new InitialContext();
     DataSource ds = (DataSource)
     Connection con = null;
         con = ds.getConnection();
         use the connection
         if (con != null)

The reference to the DataSource could be maintained, for multiple getConnection() requests. Or the DataSource can be looked up in different parts of the application code. PerUserPoolDataSourceFactory and SharedPoolDataSourceFactory will maintain the state of the pool between different lookups. This behavior may be different in other implementations.

Without JNDI

Connection pooling is useful in applications regardless of whether they run in a J2EE environment and a DataSource can be used within a simpler environment. The example below shows SharedPoolDataSource using DriverAdapterCPDS as the back end source, though any CPDS is applicable.

 public class Pool {

     private static DataSource ds;

     static {
         DriverAdapterCPDS cpds = new DriverAdapterCPDS();

         SharedPoolDataSource tds = new SharedPoolDataSource();

         ds = tds;

     public static getConnection() {
         return ds.getConnection();

This class can then be used wherever a connection is needed:

     Connection con = null;
     try {
         con = Pool.getConnection();
         use the connection
     } finally {
         if (con != null) {