2012-11-13 104 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