2

Apache 的(有用的)org.apache.commons.pool.impl.commmons.pool.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;
    }
}
4

1 回答 1

0

好吧,直接的答案就在 Javadoc 中:

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

(旁白:工厂界面似乎实际上是PooledObjectFactory,不是Poolable

那么,为什么makeObject会抛出异常呢?对象池的一个常见用例是将数据库连接池化,创建和销毁这些连接的成本很高,并且(曾经?)有时会受到软件许可(N 连接许可)的限制。创建新的数据库连接可能会抛出 SQLException,或者如果数据库服务器位于远程计算机上,则可能会抛出 IOException。makeObject 被声明为抛出异常,因此在尝试将连接放入/检索池中时,可以传递和捕获这些检查的异常。

于 2014-06-19T18:36:54.603 回答