Java Reference
In-Depth Information
In a Java EE environment, all JDBC connections come from the application server's pool. In
a Java SE environment with JPA, most JPA providers will use a connection pool transpar-
ently, and you can configure the connection pool within the persistence.xml file. In a stan-
dalone Java SE environment, the connections must be managed by the application. To deal
with that last case, you can use one of several connection pool libraries that are available
from many sources. Often, though, it is easier simply to create a connection and store it in a
thread-local variable for each thread in a standalone application.
As usual, it is important to strike the right balance here between the memory occupied by the
pooled objects, and the amount of extra GC the pooling will trigger. This is particularly true
because of the prepared statement caches. The actual connection objects may not be very big,
but statement caches (which exist on a per-connection basis) can grow to be quite big.
In this case, striking the correct balance applies to the database as well. Each connection to
the database requires resources on the database (in addition to the memory held in the applic-
ation). As connections are added to the database, the database needs more resources: it will
allocate additional memory for each prepared statement used by the JDBC driver. Database
performance can be adversely affected if the application server has too many open connec-
The general rule of thumb for connection pools is to have one connection for every thread in
the application. In an application server, start by applying the same sizing to the thread pool
and the connection pool. In a standalone application, size the connection pool based on the
number of threads the application creates. In the typical case, this will offer the best perform-
ance: no thread in the program will have to wait for a database connection to be available,
and typically there are enough resources on the database to handle the load imposed by the
If the database becomes a bottleneck, however, this rule can become counterproductive. Hav-
ing too many connections to an undersized database is another illustration of the principle
that injecting load into a busy system will decrease its performance. Using a connection pool
to throttle the amount of work that is sent to an undersized database is the way to improve
performance in that situation. Application threads may have to wait for a free connection, but
the total throughput of the system will be maximized if the database is not overburdened.
Search WWH ::

Custom Search