我的应用程序中有一个GenericKeyedObjectPool
。
我可以使用close
方法将其关闭,但是我应该如何等待客户端将每个借用的对象返回(并销毁)池中的每个对象?
我需要类似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
}