为什么GenericObjectPool.addObject会抛出已检查的异常

时间:2013-10-14 22:49:38

标签: java apache-commons

有没有任何理由说明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;
    }
}

1 个答案:

答案 0 :(得分:0)

嗯,直接答案就在Javadoc中:

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

(除此之外:工厂界面实际上似乎是PooledObjectFactory,而不是Poolable

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