2012-11-13 62 views

回答

1

GenericKeyedObjectPool创建一个包装,其中包含所需的awaitTermination方法。您可以检查closereturnObject调用,并在池关闭并返回每个对象(=当前从该池中借用的实例总数为零)时递减锁存器。

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

您应该安全地关闭它,而不必等待所有的对象返回。

GenericKeyedObjectPool.html#close()文档:

关闭池。池关闭后,borrowObject()将失败 with IllegalStateException,但returnObject(Object)和 invalidateObject(Object)将继续工作,返回的对象 将返回销毁。

+0

感谢您的回答!池中的对象是数据库/网络连接,所以如果可能的话,远程系统会更友好地关闭它们。无论如何,这让我觉得我可能不想永远等待可能永远不会退回的对象。 – palacsint