2013-10-14 109 views
2

是否有任何理由爲什麼Apache的(有用的)org.apache.commons.pool.impl.commmons.pool.GenericObjectPool.addObject()被聲明爲拋出異常?爲什麼GenericObjectPool.addObject拋出檢查異常

其實,org.apache.commons.pool.BaseObjectPool宣稱它是這樣,從org.apache.commons.pool接口:

/** 
* Create an object using the {@link PoolableObjectFactory factory} or other 
* implementation dependent mechanism, passivate it, and then place it in the idle object pool. 
* <code>addObject</code> is useful for "pre-loading" a pool with idle objects. 
* (Optional operation). 
* 
* @throws Exception when {@link PoolableObjectFactory#makeObject} fails. 
* @throws IllegalStateException after {@link #close} has been called on this pool. 
* @throws UnsupportedOperationException when this pool cannot add new idle objects. 
*/ 
void addObject() throws Exception, IllegalStateException, UnsupportedOperationException; 

爲什麼不RuntimeException的一些衍生品?

/** 
* Create an object, and place it into the pool. 
* addObject() is useful for "pre-loading" a pool with idle objects. 
*/ 
@Override 
public void addObject() throws Exception { 
    assertOpen(); 
    if (_factory == null) { 
     throw new IllegalStateException("Cannot add objects without a factory."); 
    } 
    T obj = _factory.makeObject(); 
    try { 
     assertOpen(); 
     addObjectToPool(obj, false); 
    } catch (IllegalStateException ex) { // Pool closed 
     try { 
      _factory.destroyObject(obj); 
     } catch (Exception ex2) { 
      // swallow 
     } 
     throw ex; 
    } 
} 
+0

您至少需要跟蹤諸如addObjectToPool和destroyObject之類的調用,以查看是否有一個或多個調用了Exception。至於爲什麼?誰知道......但拋出一個RuntimeException也不是一個好主意。 – TofuBeer

回答

0

那麼,直接的答案是正確的,在的Javadoc:

@throws Exception when {@link PoolableObjectFactory#makeObject} fails. 

(旁白:工廠接口似乎實際上是PooledObjectFactory,不Poolable

那麼,爲什麼makeObject拋出異常?對象池的一個常見用例是對數據庫連接進行池化,這些連接的創建和銷燬成本很高,並且有時受到軟件許可(N連接許可證)的限制。創建新的數據庫連接可能會引發SQLException,或者如果數據庫服務器位於遠程計算機上,可能會引發IOException。 makeObject被聲明爲拋出異常,因此這些被檢查的異常可以通過並在嘗試向/從池中取回/取回連接時被捕獲。

相關問題