Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Configuration

JNDI Resources and Connection Pools

Configure a container-managed JDBC DataSource in Tomcat with JNDI: Resource in context.xml, resource-ref in web.xml, lookup code, pool settings, global resources and connection leaks.

Opening a database connection takes milliseconds to seconds, and a server handling hundreds of requests per second cannot afford to do it for every request. A connection pool keeps connections open and lends them out. Tomcat can create and manage that pool for you and publish it to your application under a name, using JNDI (Java Naming and Directory Interface). Your code asks for java:comp/env/jdbc/shopDb; which database, user and pool size stand behind that name is decided by the operator in context.xml, not compiled into the WAR.

This lesson shows the configuration, the lookup code, the pool settings that matter and the classic failure, a connection leak. The Tomcat configuration is read-only; a runnable pool built on the in-memory H2 database demonstrates borrowing, returning and exhaustion.

Why use a container-managed pool?

  • Configuration outside the code. The same WAR runs in test and production with different Resource definitions.
  • One pool per resource, shared by every request thread, and optionally by all applications (global resource).
  • Secrets stay on the server, not inside the WAR.
  • Tomcat bundles a tuned pool, Tomcat DBCP (a repackaged Apache Commons DBCP2), and also supports the alternative org.apache.tomcat.jdbc.pool.DataSourceFactory.

Many frameworks (Spring Boot) create their own pool (HikariCP) from properties instead. That is equally valid; JNDI is the classic approach for WARs on a shared server.

Three pieces

Resource context.xml: URL, user, pool size
resource-ref web.xml: your app declares the name
Lookup Code asks java:comp/env/jdbc/shopDb

Put the JDBC driver JAR in CATALINA_BASE/lib.

1 / 2

Step 1: define the Resource

In conf/Catalina/localhost/shop.xml (or META-INF/context.xml):

XML
<Context>
  <Resource name="jdbc/shopDb"
            auth="Container"
            type="javax.sql.DataSource"
            driverClassName="org.postgresql.Driver"
            url="jdbc:postgresql://db.internal:5432/shop"
            username="shop_app"
            password="${shop.db.password}"
            maxTotal="25"
            maxIdle="10"
            minIdle="5"
            maxWaitMillis="8000"
            validationQuery="SELECT 1"
            testOnBorrow="true"
            removeAbandonedOnBorrow="true"
            removeAbandonedTimeout="60"
            logAbandoned="true" />
</Context>

The ${shop.db.password} placeholder is replaced from a system property (-Dshop.db.password=... in CATALINA_OPTS), keeping the password out of the file in version control. Many teams also restrict file permissions on conf to the Tomcat user.

Put the JDBC driver JAR in CATALINA_BASE/lib (common loader), not in the WAR: the pool is created by Tomcat, outside your application's class loader, so it must find the driver there. (A driver in WEB-INF/lib is invisible to the container-created pool.)

Step 2: declare it in the application

XML
<resource-ref>
  <description>Shop database</description>
  <res-ref-name>jdbc/shopDb</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

Servlet 3 and later also allow @Resource(name = "jdbc/shopDb") injection on a servlet field, in which case no resource-ref is strictly required.

Step 3: look it up and use it

Java
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class ShopRepository {
    private final DataSource dataSource;

    public ShopRepository() throws Exception {
        Context env = (Context) new InitialContext().lookup("java:comp/env");
        this.dataSource = (DataSource) env.lookup("jdbc/shopDb");
    }

    public int countProducts() throws Exception {
        try (var connection = dataSource.getConnection();            // borrowed from the pool
             var statement = connection.createStatement();
             var rs = statement.executeQuery("SELECT COUNT(*) FROM product")) {
            rs.next();
            return rs.getInt(1);
        }                                                             // close() returns it to the pool
    }
}

The crucial detail is the try-with-resources: calling close() on a pooled connection does not close the physical connection; it hands it back. Forgetting it leaks the connection forever.

A pool you can run

The stand-in below builds a tiny pool on H2's in-memory database with a blocking queue: maxTotal connections, a borrow timeout like maxWaitMillis, and a proxy-style close() that returns the connection. A second part shows what a leak looks like.

Java A miniature connection pool on H2 (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In production the symptom is exactly this: after hours of traffic every request waits maxWaitMillis and then fails with Cannot get a connection, pool error Timeout waiting for idle object. The remedies are try-with-resources everywhere, and as a safety net removeAbandonedOnBorrow="true" with logAbandoned="true", which makes the pool reclaim connections held too long and log the stack trace of the code that borrowed them.

Pool settings explained

Attribute Meaning
maxTotal Maximum connections (DBCP2 name; maxActive in the Tomcat JDBC pool). Keep it below the database's own limit divided by the number of servers.
maxIdle, minIdle How many idle connections to keep.
maxWaitMillis How long a request waits for a free connection before failing.
validationQuery, testOnBorrow Check a connection before lending it, so connections killed by a firewall or DB restart are replaced.
timeBetweenEvictionRunsMillis, minEvictableIdleTimeMillis Background cleanup of idle connections.
removeAbandonedOnBorrow, removeAbandonedTimeout, logAbandoned Leak detection and recovery.

A good starting point for a pool is small: 10 to 30 connections for most applications. A database serving 20 queries at once is usually faster than one juggling 200.

To share one pool among several applications, define the resource once in server.xml under <GlobalNamingResources> and give each application a link:

XML
<!-- server.xml -->
<GlobalNamingResources>
  <Resource name="jdbc/sharedDb" auth="Container" type="javax.sql.DataSource" ... />
</GlobalNamingResources>

<!-- context.xml of each app -->
<ResourceLink name="jdbc/shopDb" global="jdbc/sharedDb" type="javax.sql.DataSource" />

The application still looks up java:comp/env/jdbc/shopDb. Other JNDI entry types include Environment (simple values such as strings and numbers), Resource for mail sessions (javax.mail.Session) and custom object factories.

How JNDI lookups work: a registry

The final stand-in models the idea: a registry keyed by name with a java:comp/env prefix, an operator who binds a "DataSource", and an application that only knows the name.

Java JNDI as a name registry (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • JDBC driver only in WEB-INF/lib, so the pool says Cannot load JDBC driver class.
  • Forgetting close(), causing pool exhaustion.
  • Names without the java:comp/env/ prefix in the lookup (when using InitialContext directly).
  • A pool larger than the database's connection limit, so the database refuses connections under load.
  • Passwords in plain text inside META-INF/context.xml in the WAR.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the JDBC driver JAR go for a Tomcat-managed DataSource?

    The container creates the pool outside the web app's class loader, so it must find the driver on the common class path.
  2. 2. What does close() on a pooled connection do?

    The pool wraps the connection so close() hands it back for reuse. Skipping it leaks the connection.
  3. 3. Which lookup name is correct from application code?

    Container-managed resources are bound under the java:comp/env namespace of the application.
  4. 4. What do removeAbandonedOnBorrow and logAbandoned help with?

    They reclaim connections held too long and log where they were borrowed.

Summary

  • A <Resource> in context.xml defines the pool; resource-ref or @Resource declares it; code looks it up under java:comp/env.
  • The driver JAR belongs in CATALINA_BASE/lib.
  • Always close connections (try-with-resources) so the pool gets them back; enable leak detection as a safety net.
  • Keep pools small and match them to database limits; validate connections on borrow.
  • Share a pool with GlobalNamingResources and ResourceLink; keep passwords out of the WAR.

Next: Logging and access logs