Use of the Apache object pool

Source: Internet
Author: User

Apache Commons-pool is essentially an "object pool" that maintains a container of object collections through certain rules; Commos-pool in many scenarios, to implement "connection pooling"/"task worker pool" and so on, everyone commonly used DBCP database connection pool,    is also based on Commons-pool implementations. Commons-pool implementation of the idea is very simple, its main role is to pool the "object collection", any object access through the pool operation, will be in strict accordance with the "Pool configuration" (such as the size of pools) real-time object/block control/Destroy objects and so on. To a certain extent,    Implements the management of object collections and the distribution of objects.    1) The way to create objects, using the Factory mode; 2) using "Pool Configuration" to constrain object access 3) Save the list of objects in the queue (LinkedList) preferred to declare, different "object pool" (or connection pool) in the design may have a big difference, but in the same thinking, this article mainly explains Commons-po OL, the difference between it and other "connection pooling" is not discussed much here. I. Object lifecycle Apache-common pool usage two. config: maxactive: The maximum number of connections in a linked pool, default is 8.maxIdle: The maximum number of idle connections in a linked pool, and the default is 8.minIdle: The minimum number of idle connections in the connection pool , the default is 0.maxWait: When the connection pool resource is exhausted, the caller is blocked for the maximum time, and the timeout runs out of the exception. units, milliseconds; The default is-1. Minevictableidletimemillis: The minimum time that the connection is idle, the idle connection may be removed after this value is reached. A negative value (-1) indicates that it is not removed. Softminevictableidletimemillis: The minimum time that the connection is idle, when this value is reached, the idle link is removed and the number of "Minidle" idle connections is retained. The default is -1.numtestsperevictionrun: The number of linked resources that are detected each time for the idle link detection thread. The default is 3.testOnBorrow: When the "link" resource is output to the caller, the detection is valid, if it is invalid, it is removed from the connection pool and an attempt is made to obtain a continuation fetch. The default is False. It is recommended that you leave the default value. Testonreturn: When you "return" a link to a connection pool, the validity of the linked object is detected. The default is False. It is recommended that you leave the default value. Testwhileidle: When the link object is output to the caller, its idle timeout is detected, and the default is False. If the chain"Idle timeout will be removed. It is recommended that you leave the default value. Timebetweenevictionrunsmillis: "Idle link" detects the thread, the period of detection, and the number of milliseconds. A negative value indicates that the detection thread is not running. The default is-1. Whenexhaustedaction: When the number of active in the connection pool reaches the threshold, that is, when the "link" resource is exhausted, the connection pool needs to take the means that the default is 1:-0: Throw exception, 1: block until a link resource is available, 2: Mandatory Create a new linked resource these properties can be set in Org.apache.commons.pool.impl.GenericObjectPool.Config. Three. Principle analysis 1) Object pool creation (ref. Genericobjectpool):p ublic Genericobjectpool (Poolableobjectfactory factory, Genericobjectpool.config Config): This method creates an Genericobjectpool instance, and the Genericobjectpool class has implemented all the core operations associated with the object pool. Developers can use it in a way that inherits or encapsulates it. With this constructor, we can clearly see that a pool needs to specify the Poolableobjectfactory instance, And the config information for this object pool. Poolableobjectfactory is primarily used to create new objects, such as when objects in an object pool are low, you can use the Poolableobjectfactory.makeobject () method to create objects.    and delivered to pool management. This constructor instantiates a linkedlist as the "Object Pool" container, which is used to access "objects". It also determines whether a background thread is started based on the value of Timebetweenevictionrunsmillis. This thread is used to periodically scan the list of objects in the pool to see if the "Objects in object Pools" idle (idle) time has reached the threshold and, if so, removes the object. Java code if ((Getminevictableidletimemillis () > 0) && (Idletimemilis > Getminevictableidletimemillis ())) {Removeobject = tRue      } ... if (removeobject) {try {_factory.destroyobject (pair.value); } catch (Exception e) {//ignored}} 2) object Factory Poolableobjectfactory interface: Commons-pool by using Objectfacto The RY (Factory mode) method decouples the creation/detection/destruction of objects in the object pool, which is a very good design idea. This interface has an abstract class basepoolableobjectfactory that can be inherited and implemented by developers. Object Makeobject (): Creates a new object, and when the number of objects in the object pool is insufficient, this method is used to "output" a new "object" and to be delivered to the object pool management. Void Destroyobject (Object obj): Destroying objects, If an object is detected as idle in the object pool time-out, or the object is detected as invalid when the operator "returns the object" to the object pool, the object is destroyed at this point; The action design of the Destroy object is far apart, but it must be clear: when this method is called, the life cycle of the object must end. If object is a thread, then the thread must exit, and if object is a socket operation, then the socket must be closed; If object is a file stream operation, then data flush is turned off gracefully. Boolean Validateobject (Object obj): Detects if the object is "valid"; Invalid "Object" cannot be saved in pool, so "background detection thread" periodically detects the validity of "object" in pool, causes the object to be removed from the pool and destroy if the object is invalid, and also detects the object when the caller gets an "object" from the pool To ensure that the object cannot be output to the caller without saying "invalid", and that the object's validity will still be detected when the caller has finished using the object back to the pool. The so-called validity is whether the state of this "object" is expected to be used directly by the caller, or if the object is a socket, Then its effectiveness is whether the channel of the socket is unblocked/blocked or not. void Activateobject (Object obj): An "Activation" object, when the pool decides to remove an object from being delivered to the caller, an additional "activate" operation, such asThe "reset" parameter list in the Activateobject method feels like a "newly created" object when used by the caller, and if object is a thread, you can reset the thread break token in the activation operation, or let the thread wake from the block, and so on; object is a socket, you can refresh the channel in the activation action, or link the socket to rebuild (if the socket unexpectedly shuts down). void void Passivateobject (object obj): "passivated" object when the caller "Return to the object", the pool will be "passivation object"; The implication of passivation is that this "object" needs to "rest" for the time being. If object is a socket, you can clear buffer in passivateobject and block the socket;    If object is a thread, you can sleep the thread in the "passivation" operation or wait for an object in the thread. Note that Activateobject and passivateobject two methods need to correspond to avoid deadlocks or "object" state confusion. 3) Objectpool interface and implementation: The object pool is the core interface of Commons-pool, used to maintain "object list" Access, where Genericobjectpool is its implementation class, it has implemented the relevant functions.  Object Borrowobject (): Gets an object from the pool, which causes an "object" to be removed from the pool (out of pool management), which can be used after the "object" reference is obtained, and "returned" after the use is finished. Pseudocode: Java code      Public Object Borrowobject () throws Exception {object value = NULL;          Synchronized (this) {if (!_pool.isempty ()) {value = _pool.remove (); }} for (;;)                  {//If there is no "object" in the pool, it is based on the appropriate "exhaustion" policy if (value = = null) {switch (whenexhaustedaction) { IfExhausted, still continue to create new "Object" Case When_exhausted_grow:value = _factory.makeobject ();                  Break                  If it is exhausted, it terminates and exits in an unusual manner.                  Case When_exhausted_fail:throw New Nosuchelementexception ("Pool exhausted"); If exhausted, block until an "object" is returned to case When_exhausted_block:try {synch Ronized (value) {if (value = = null) {//maxwait is specified in config "                                  Maximum wait Time "if (maxwait <= 0) {latch.wait ();                                  } else {latch.wait (waitTime);                              }} else {break;  }}} catch (Interruptedexception e) {                               Break } default://}} try {_factory.activ              Ateobject (Latch.getpair (). value);  if (_testonborrow &&!_factory.validateobject (Latch.getpair (). Value)) {throw              New Exception ("Validateobject failed");          } return value;              } catch (Throwable e) {try {_factory.destroyobject (Latch.getpair (). value);  } catch (Throwable e2) {//}}}}, void Returnobject (Object obj): The "return" object, when the "object" is used, needs to be returned to the pool in order to maintain the number of objects in the pool can be controlled, if not returned to the pool, it will mean that there will be a large number of "objects" outside the pool, then the meaning of "object pool" is used. The following is pseudo-code: Java code public void Returnobject (Object obj) throws Exception {try {boolean success = true;//if ( _testonreturn &&! (_factory.validateobject (obj))) {             Success = false;          } else {_factory.passivateobject (obj);              } synchronized (this) {//detects whether the number of objects already idle in the pool has reached the threshold.              if ((_maxidle >= 0) && (_pool.size () >= _maxidle)) {success = false;              } else if (success) {_pool.addfirst (new Objecttimestamppair (obj)); }}//Destroy The instance if necessary if (!success) {try {_              Factory.destroyobject (obj);      } catch (Exception e) {//ignored}}} catch (Exception e) {// }} void Invalidateobject (Object obj): Destroys objects, calling Objectfactory.destroyobject (obj) directly;.    void AddObject (): Developers can call the AddObject method directly to create an "object" and add it to the pool. Four. Code instance.    This example is used primarily to demonstrate a "TCP connection pool."  1) ConnectionPoolFactory.java:Java code import org.apache.commons.pool.BasePoolableObjectFactory; Import Org.apache.commons.pool.impl.GeNericobjectpool;    Import Org.apache.commons.pool.impl.GenericObjectPool.Config;        public class Connectionpoolfactory {private Genericobjectpool pool; Public Connectionpoolfactory (Config config,string ip,int port) {ConnectionFactory factory = new ConnectionFactory          (IP, port);      Pool = new Genericobjectpool (factory, config);      } public Socket getconnection () throws exception{return (socket) pool.borrowobject ();          } public void Releaseconnection (socket socket) {try{pool.returnobject (socket);                  }catch (Exception e) {if (socket! = NULL) {try{socket.close ();       }catch (Exception ex) {//}}}}/**            * Inner * @author Qing * * */class ConnectionFactory extends Basepoolableobjectfactory {    Private inetsocketaddress address;                Public ConnectionFactory (String Ip,int port) {address = new inetsocketaddress (IP, port); } @Override Public Object makeobject () throws Exception {Socket socket = n              EW Socket ();              Socket.connect (address);          return socket;                  } public void Destroyobject (Object obj) throws Exception {if (obj instanceof Socket) {              (Socket) obj. Close ();                  }} public boolean validateobject (Object obj) {if (obj instanceof Socket) {                  Socket socket = ((socket) obj);                  if (!socket.isconnected ()) {return false;                  } if (socket.isclosed ()) {return false;              } return true;          } return false; }}} 2) Testmain.java (test Class): Java code public CLASS Testmain {/** * @param args */public static void main (string[] args) {config config =          New Config ();          config.maxactive = 16;          Config.maxwait = 30000;          Connectionpoolfactory poolfactory = new connectionpoolfactory (config, "127.0.0.1", 8011);          Socket socket = NULL;              try{socket = poolfactory.getconnection ();          }catch (Exception e) {e.printstacktrace ();              }finally{if (socket! = NULL) {poolfactory.releaseconnection (socket);   }          }        }    }

Use of the Apache object pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.