0

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();

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.