Question

Take a look at the following code. 1. I am creating a connection pool to stardog
2. Obtaining a connection from the pool. 3. Returning the connection to pool after the use.

My question is what will happen if I do aConn.close() instead of returning to the pool.

 ConnectionConfiguration aConnConfig = ConnectionConfiguration
.to("testConnectionPool")
.credentials("admin", "admin");

ConnectionPoolConfig aConfig = ConnectionPoolConfig
   .using(aConnConfig)
   .minPool(10)
   .maxPool(1000)
   .expiration(1, TimeUnit.HOURS)   
   .blockAtCapacity(1, TimeUnit.MINUTES);

// now i can create my actual connection pool
ConnectionPool aPool = aConfig.create();

// if I want a connection object...
Connection aConn = aPool.obtain();

// now I can feel free to use the connection object as usual...

// and when I'm done with it, instead of closing the connection, 
//I want to return it to the pool instead.
aPool.release(aConn);

// and when I'm done with the pool, shut it down!
aPool.shutdown();

what happends if I close the connection by aConn.close();

The main reason I am asking whenever I use connection in any classes I dont have the pool object to do aPool.release(aConn);

Is it recommended to do . Will it spoil the use of pooling.

Était-ce utile?

La solution

If you close the connection directly the pool will still have a reference to the Connection because it has not been released, so while the Connection will close its resources, the Pool will retain the reference and you'll probably be leaking memory over time.

The suggested way to deal with this is when you obtain a Connection from the Pool, wrap it using DelegatingConnection:

public final class PooledConnection extends DelegatingConnection {
    private final ConnectionPool mPool;
    public PooledConnection(final Connection theConnection, final ConnectionPool thePool) {
        super(theConnection);
        mPool = thePool;
    }

    @Override
    public void close() {
        super.close();
        mPool.release(getConnection());
    }
}

This way you can simply close the Connection in the code that uses it and it will correctly release back into the pool and you don't have to worry about passing around the reference to the pool.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top