becomes much more predictable, because it won't degenerate rapidly due to
the exhaustion of memory.
Let's look at the steps involved in using connection pooling.
Once at initialization
Import the appropriate packages . We need the packages for JDBC
access and Java Naming and Directory Interface ( JNDI ), because data
sources are named objects.
Create the naming context. This is a JNDI call to establish a naming
context for the data source.
Get a data source. This is a factory object that will be used to create
connections or get them from the connection pool as needed. It is a
JNDI named resource.
Once per connection
Get a connection from the data source. This method will actually get a
connection from a pool if an active connection exists; otherwise, it will
Close the connection. This method maintains the connection, but frees
it to the connection pool.
Refactoring our BBS to add pooled connections
The program in listing 7.2 demonstrates how to use connection pooling with
Java 1.2. Most programming environments allow you to use a wizard to create
a database application that pools connections. Our program was taken from a
WebSphere application. The JDBC access can be vendor neutral; the JNDI
access, however, will probably have some vendor-specific libraries, but you
should use the common JNDI interface.
Here, we see connection pooling in practice. At a high level, we're creating
a naming context (for the JNDI ), a data source, and a factory. The factory is
bound to the data source (a named resource that we can find through the
JNDI ). We then use that pair to create a connection.