我的申请表中有GenericKeyedObjectPool
。
我可以使用close
方法关闭它但是我应该如何等待客户端返回(并且池销毁)每个借用的对象到池中?
我需要像ExecutorService.awaitTermination
这样的东西。
答案 0 :(得分:2)
为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
}
答案 1 :(得分:1)
关闭它应该是安全的,而不是等待返回所有对象。
来自GenericKeyedObjectPool.html#close()的文档:
关闭游泳池。池关闭后,borrowObject()将失败 使用IllegalStateException,但返回Object(Object)和 invalidateObject(Object)将继续使用返回的对象 在返回时被摧毁。