2013-10-14 3 views
2

Y a-t-il une bonne raison pour laquelle Apache (utile) org.apache.commons.pool.impl.commmons.pool.GenericObjectPool.addObject() est déclaré pour lancer Exception?Pourquoi GenericObjectPool.addObject est-il vérifié? Exception

En fait, org.apache.commons.pool.BaseObjectPool déclare comme tel, de l'interface 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; 

Pourquoi pas un dérivé de 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

Vous auriez besoin, à tout le moins, de suivre les appels comme: addObjectToPool et destroyObject pour voir si un ou plusieurs d'entre eux lance une exception. Quant à pourquoi? Qui sait ... mais lancer une RuntimeException n'est pas une bonne idée non plus. – TofuBeer

Répondre

0

Eh bien, la réponse directe est là dans le Javadoc:

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

(côté: l'interface usine semble être en fait PooledObjectFactory, pas Poolable)

Alors, pourquoi ne makeObject jeter Exception? Un cas d'utilisation courant pour les pools d'objets consiste à mettre en commun des connexions de base de données, qui sont coûteuses à créer et à détruire et sont (étaient?) Parfois limitées par des licences logicielles (une licence N-connection). Créer une nouvelle connexion de base de données peut lancer SQLException, ou peut-être IOException si le serveur de base de données se trouve sur une machine distante. makeObject est déclaré lancer une exception afin que ces exceptions vérifiées puissent être passées et interceptées lors de la tentative de mise en/hors service d'une connexion vers/depuis le pool.

Questions connexes