PoolableObjectFactory几个方法的总结

PoolableObjectFactory的几个方法总结

An interface defining life-cycle methods for instances to be served by an ObjectPool.

By contract, when an ObjectPool delegates to a PoolableObjectFactory,

  1. makeObject is called whenever a new instance is needed.
  2. activateObject is invoked on every instance that has been passivated before it is borrowed from the pool.
  3. validateObject is invoked on activated instances to make sure they can be borrowed from the pool. validateObject may also be used to test an instance being returned to the pool before it is passivated. It will only be invoked on an activated instance.
  4. passivateObject is invoked on every instance when it is returned to the pool.
  5. destroyObject is invoked on every instance when it is being "dropped" from the pool (whether due to the response from validateObject, or for reasons specific to the pool implementation.) There is no guarantee that the instance being destroyed will be considered active, passive or in a generally consistent state.

参考:http://commons.apache.org/proper/commons-pool/api-1.6/org/apache/commons/pool/PoolableObjectFactory.html

对于使用pool来说基本流程:

 Object obj = null;

 try {
     obj = pool.borrowObject();
     try {
         //...use the object...
     } catch(Exception e) {
         // invalidate the object
         pool.invalidateObject(obj);
         // do not return the object to the pool twice
         obj = null;
     } finally {
         // make sure the object is returned to the pool
         if(null != obj) {
             pool.returnObject(obj);
        }
     }
 } catch(Exception e) {
       // failed to borrow an object
 }

调用 pool的borrowObject()会触发内部调用poolableObjectFactory,基本流程如下:

1. 调用makeObject()获取对象,一般需要实现。

2. 调用activateObject(),默认是一个空实现。

调用 pool的returnObject()会触发内部调用poolableObjectFactory,基本流程如下:

1. 调用validateObject()确保对象有效,默认实现返回True。

2. 调用passivateObject()让对象钝化,默认是一个空实现,貌似也没啥用。

2. 如果validateObject()返回False,调用destroyObject()。

猜你喜欢

转载自san-yun.iteye.com/blog/1940972