Apache's Commons-pool pool creates multi-threaded use WebClient

Source: Internet
Author: User
Tags throw exception

package test;import org.apache.commons.pool.poolableobjectfactory;import  org.apache.commons.pool.impl.genericobjectpool;import org.apache.log4j.logger;import  com.gargoylesoftware.htmlunit.browserversion;import  com.gargoylesoftware.htmlunit.nicelyresynchronizingajaxcontroller;import  Com.gargoylesoftware.htmlunit.webclient;//http://blog.csdn.net/m13321169565/article/details/8081410public  class pooledclientfactory{    private static logger log =  logger.getlogger (Pooledclientfactory.class);    private final static  Pooledclientfactory instance =new pooledclientfactory ();     //Another option might be more appropriate-- -Object pooling technology.     //Apache-based Commons-pool Pool     private final  Genericobjectpool clientpool =new genericobjectpool ();    public  Static pooledclientfactory getInstance ()  {        return instance;     }        public pooledclientfactory () {                 //implementing object Pool object creation factory interface          clientpool.setfactory (New poolableobjectfactory ()  {              //  create an object instance for populating the object pool. You can also assign the resources to which this object applies.                @Override              public object makeobject ()  throws  Exception  {                 log.info ("For Thread  [ "  + thread.currentthread (). GetName () +                           " ]  Create a new WebClient instance! ");                                   WebClient  Webclient = new webclient (browserversion.firefox_17);                                           // Set parameters for WebClient                      webclient.getcookiemanager (). Setcookiesenabled (True);//  turn on cookie management                       webclient.getoptions(). Setjavascriptenabled (True);//  turn on JS parsing                      webclient.getoptions (). setcssenabled (False);                     //   When http error occurs, the program does not throw an exception to continue execution                      webclient.getoptions (). Setthrowexceptiononfailingstatuscode ( False);                     //  prevent JS syntax errors from throwing Exceptions                      webclient.getoptions (). Setthrowexceptiononscripterror (false);  // js If an exception is thrown when running an error                  &nBsp;   webclient.getoptions (). SetTimeout (10000);                     //  default is false,  Set to True to not let your browsing behavior be recorded                      webclient.getoptions (). setdonottrackenabled (False);                     //  Setting up AJAX asynchronous processing controller enables AJAX support                      webClient                             . Setajaxcontroller (New nicelyresynchronizingajaxcontroller ());                     return webclient;             }                          //  destroy object, called when destroying object pool, connection pool call Invalidateobject (obj) When called               @Override              public void destroyobject (OBJECT ARG0)  throws Exception {                   log.info ("Destroy object:"  + arg0);                   WebClient client =  ( WebClient)  arg0;                 client.closeallwindows();                 client  = null;            }                          //   Query object validation, requires object pool setting Settestonborrow (TRUE), invalid object will be destroy              @Override              public boolean validateobject (object arg0)  {                  log.info ("Check object validity:"  +  ARG0);                   return true;            }               //  activates an object that is called when an object is fetched from an object pool                 @Override              public void activateobject (object arg0)  throws Exception  {                  Log.info ("active object:"  + arg0);               }                          //  Suspend (passivation) an object that is called when the object is returned to the object pool               @Override              public void passivateobject (object arg0)  throws Exception  {                                  log.info ("Suspended object:"  + arg0);               }         });                 clientpool.settestonborrow (true);         //the maximum waiting time for the loan object to reach the maximum value, 5s wait time after throw exception         //clientpool.setmaxwait (;   )      //set the maximum number of available loans, default is 8         Clientpool.setmaxactive (Ten);    }                              public webclient getclient ()   {        try {             return  (WebClient) this.clientPool.borrowObject ();         } catch  (exception e)  {             e.printstacktrace ();             return null;        }             }        public void  returnclient (webclient client)  {        try {             this.clientpool.returnobject (client);         } catch  (exception e)  {        &nbSp;    e.printstacktrace ();        }         }          //test Object Pool        public static void main (String[] args)  {           try {               //CursorableLinkedList             //gets the number of idle objects in the pool, and returns negative if not available                  log.info (Pooledclientfactory.getinstance (). ClientPool.getNumIdle ());                         //Remove Object 1        object obj1=     pooledclientfactorY.getinstance (). Getclient ();         //Remove Object 2         object obj2=    pooledclientfactory.getinstance (). GetClient () ;         //Remove Object 3                 Object obj3=     Pooledclientfactory.getinstance (). Getclient ();                 //if the object loan reaches the maximum number of maxactive, the program waits for the object to be available (returned), or you can set the wait time by default_max_wait. Default is-11 straight wait                  Pooledclientfactory.getinstance (). Getclient ();                     pooledclientfactory.getinstance (). GetClient ();                     pooledclientfactory.getinstance (). GetClient ();                      pooledclientfactory.getinstance (). Getclient ();                     pooledclientfactory.getinstance (). Getclient ();                     pooledclientfactory.getinstance (). Getclient ();                 //Returning Objects 1                                      pooledclientfactory.getinstance (). Returnclient ((WebClient)  obj1);                 //get the number of free objects in the pool          log.info (Pooledclientfactory.getinstance (). ClientPool.getNumIdle ());          //     returns the number of objects loaned from the pool          log.info (Pooledclientfactory.getinstance (). Clientpool.getnumactive ());                 //maximum number of loans available          log.info (Pooledclientfactory.getinstance (). ClientPool.getMaxActive () );         //Maximum idle quantity          Log.info (Pooledclientfactory.getinstance (). Clientpool.getmaxidle ());         //Minimum Idle quantity         log.info (Pooledclientfactory.getinstance (). Clientpool.getminidle ());                          pooledclientfactory.getinstance (). Clientpool.clear ();         pooledclientfactory.getinstance (). Clientpool.close ();                 //using a factory to create an object          pooledclientfactory.getinstance (). Clientpool.getmaxactive ();         } catch  (exception e)  {                          E.printstacktrace ();        }             }}


This article is from the "bit accumulation" blog, please be sure to keep this source http://tianxingzhe.blog.51cto.com/3390077/1792545

Apache's Commons-pool pool creates multi-threaded use WebClient

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.