Sumanth
Sumanth

Reputation: 605

Database Connection pooling in a Java application running under JBOSS application server

I am trying to understand database connection pool in a java application which is deployed under JBOSS. Btw there is no issue with database connection. A database connection pool is setup in JBOSS application server like below:

<datasource jta="false" jndi-name="java:/testDS" pool-name="testDS" enabled="true" use-java-context="true">
       <connection-url>jdbc:oracle:thin:@xxx</connection-url>
       <driver>oracle</driver>
       <pool>
             <min-pool-size>2</min-pool-size>
             <max-pool-size>15</max-pool-size>
             <prefill>true</prefill>
       </pool>
       <security>
             <user-name>admin</user-name>
             <password>admin</password>
       </security>
</datasource>

Then my java code to get the connection looks like below:

String jndiName = "java:/testDS";
InitialContext jndiCntx = new InitialContext();
DataSource ds = (DataSource) jndiCntx.lookup(jndiName);
Connection connection = ds.getConnection();

Does the above code make use of connectionpool? If it is, what is the purpose of the below code? I am a bit confused. What is the difference between these 2 code snippets?

InitialContext jndiCntx = new InitialContext();
ConnectionPoolDataSource cpds = (ConnectionPoolDataSource) jndiCntx.lookup(jndiName);            
PooledConnection pc = cpds.getPooledConnection();
Connection connection = pc.getConnection();

Upvotes: 0

Views: 1191

Answers (1)

Stefan Gro&#223;mann
Stefan Gro&#223;mann

Reputation: 1026

If you look at the JavaDoc at PooledConnection ( http://docs.oracle.com/javase/7/docs/api/javax/sql/PooledConnection.html) which is returned by ConnectionPoolDataSource you can read:

An application programmer does not use the PooledConnection interface directly; rather, it is used by a middle tier infrastructure that manages the pooling of connections.

When an application calls the method DataSource.getConnection, it gets back a Connection object. If connection pooling is being done, that Connection object is actually a handle to a PooledConnection object, which is a physical connection.

The typical usage of a datasource looks like this:

@Stateless
public class MyBean {

    @Resource(lookup = "java:/testDS")
    private DataSource dataSource;

    public void testDatasource() {
        try (Connection connection = dataSource.getConnection()) {

            // use the connection 

        } catch (SQLException e) {
            throw new SomeRuntimeException(e);
        }
    }
}

Important is that your close the connection after using. The best way is an try-autoclose. Otherwise your server runs out of connections.

Using "@Statless" initiates a transaction.

Upvotes: 3

Related Questions