我的应用程序中有一个GenericKeyedObjectPool
。 我可以用close
方法关闭它,但我该如何等待客户返回池(并且池会销毁)每个借用对象到池中?如何安全关闭GenericKeyedObjectPool?
我需要类似ExecutorService.awaitTermination
。
我的应用程序中有一个GenericKeyedObjectPool
。 我可以用close
方法关闭它,但我该如何等待客户返回池(并且池会销毁)每个借用对象到池中?如何安全关闭GenericKeyedObjectPool?
我需要类似ExecutorService.awaitTermination
。
为GenericKeyedObjectPool
创建一个包装,其中包含所需的awaitTermination
方法。您可以检查close
和returnObject
调用,并在池关闭并返回每个对象(=当前从该池中借用的实例总数为零)时递减锁存器。
public final class ListenablePool<K, V> {
private final GenericKeyedObjectPool<K, V> delegate;
private final CountDownLatch closeLatch = new CountDownLatch(1);
private final AtomicBoolean closed = new AtomicBoolean();
public ListenablePool(final KeyedPoolableObjectFactory<K, V> factory) {
this.delegate = new GenericKeyedObjectPool<K, V>(factory);
}
public V borrowObject(final K key) throws Exception {
return delegate.borrowObject(key);
}
public void returnObject(final K key, final V obj) throws Exception {
try {
delegate.returnObject(key, obj);
} finally {
countDownIfRequired();
}
}
private void countDownIfRequired() {
if (closed.get() && delegate.getNumActive() == 0) {
closeLatch.countDown();
}
}
public void close() throws Exception {
try {
delegate.close();
} finally {
closed.set(true);
countDownIfRequired();
}
}
public void awaitTermination() throws InterruptedException {
closeLatch.await();
}
public void awaitTermination(final long timeout, final TimeUnit unit)
throws InterruptedException {
closeLatch.await(timeout, unit);
}
public int getNumActive() {
return delegate.getNumActive();
}
// other delegate methods
}
您应该安全地关闭它,而不必等待所有的对象返回。
从GenericKeyedObjectPool.html#close()文档:
关闭池。池关闭后,borrowObject()将失败 with IllegalStateException,但returnObject(Object)和 invalidateObject(Object)将继续工作,返回的对象 将返回销毁。
感谢您的回答!池中的对象是数据库/网络连接,所以如果可能的话,远程系统会更友好地关闭它们。无论如何,这让我觉得我可能不想永远等待可能永远不会退回的对象。 – palacsint