2013-04-10 110 views
1

请看下面的代码。 1.我正在创建连接池stardog
2.从池中获取连接。 3.使用后返回连接池。如果我从stardog连接池关闭连接,会发生什么情况

我的问题是,如果我做aConn.close(),而不是返回到池中会发生什么。

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

如果我附近aConn.close();

主要的原因我问每当我使用任何课程方面,我没有这个池对象做aPool.release(aConn);

最好先连接什么happends做。 它会破坏池的使用。

回答

2

如果关闭直接连接池仍然要连接一个参考,因为它没有被释放,所以当连接将关闭其资源池将保留提及,你可能会泄漏内存随着时间的推移。

建议的方式来处理,这是当你从池中获取一个连接,使用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()); 
    } 
} 

这样,你可以简单地关闭在使用它,它会在代码中的连接正确地释放回池中,并且不必担心传递给池的参考。

+0

谢谢,这是一个清晰的想法。 – 2013-04-10 13:43:45

+0

请接受答案,让其他人知道这是正确的信息。 – Michael 2013-04-10 13:51:46

+0

保持关闭连接的池将会产生其他问题?就像另一个类请求连接一样,并且池提供了一个关闭的连接,它将以一个关闭的连接异常结束。 – 2013-04-10 13:53:07

相关问题