[英]What happens if I close a connection from connection pool of stardog
看一下下面的代码。 1.我正在创建与stardog的连接池
2.从池中获取连接。 3.使用后将连接返回到池中。
我的问题是,如果我执行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();
关闭连接会发生什么aConn.close();
每当我在任何类中使用连接时,我问的主要原因是我没有池对象来执行aPool.release(aConn);
是否建议这样做。 它会破坏池的使用吗?
如果直接关闭连接,则由于尚未释放该连接池,因此该池仍将具有对该连接的引用,因此尽管该连接将关闭其资源,但该池将保留该引用,并且随着时间的流逝,您可能会泄漏内存。
建议的解决方法是从池中获取连接时,使用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());
}
}
这样,您可以简单地关闭使用它的代码中的Connection,它将正确地释放回池中,而您不必担心将引用传递给池。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.