commons.pool2 The use of object pools

?
1
2
3
4
5
< dependency >
     < groupId >org.apache.commons</ groupId >
     < artifactId >commons-pool2</ artifactId >
     < version >2.3</ version >
</ dependency >

Pool object factory  PooledObjectFactory And pool objects  DefaultPooledObject

Let's start with a concept :

Pool object factory (PooledObjectFactory Interface ): Used to create pool objects , Passivate unused pool objects (passivateObject), Activate the pool object to be used (activeObject), Validate pool objects (validateObject), Destroy the pool object in question (destroyObject) Etc

PooledObjectFactory It's a pooled object factory interface , The generation object is defined 、 Activate the object 、 Passivation object 、 How to destroy objects , as follows

?
1
2
3
4
5
6
7
8
9
10
11
public interface PooledObjectFactory< T > {
     PooledObject< T > makeObject() throws Exception;
 
     void destroyObject(PooledObject< T > var1) throws Exception;
 
     boolean validateObject(PooledObject< T > var1);
 
     void activateObject(PooledObject< T > var1) throws Exception;
 
     void passivateObject(PooledObject< T > var1) throws Exception;
}

If needed Commons-Pool, Then you need to provide a PooledObjectFactory The concrete implementation of the interface . A relatively simple way is , Inherit BasePooledObjectFactory This abstract class . And inheriting this abstract class , Only two methods need to be implemented :create() and wrap(T obj).

Realization create() It's easy , To achieve wrap(T obj) There are also shortcuts , You can use classes DefaultPooledObject, The code can refer to the following :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import  org.apache.commons.pool2.BasePooledObjectFactory;
import  org.apache.commons.pool2.PooledObject;
import  org.apache.commons.pool2.impl.DefaultPooledObject;
 
/**
  * Created by liyanxin on 2015/3/25.
  */
public  class  PooledStringBufferFactory  extends  BasePooledObjectFactory<StringBuffer> {
 
     @Override
     public  StringBuffer create()  throws  Exception {
         return  new  StringBuffer( 16 );
     }
 
     @Override
     public  PooledObject<StringBuffer> wrap(StringBuffer stringBuffer) {
         return  new  DefaultPooledObject<StringBuffer>(stringBuffer);
     }
}

Of course, there are other pool object factories , Such as KeyedPooledObjectFactory, and PooledObjectFactory Similar interface , It's just that there's more in the relevant methods Key Parameters , as follows ,

?
1
2
3
4
5
6
7
8
9
10
11
12
public  interface  KeyedPooledObjectFactory<K,V> {
    
     PooledObject<V> makeObject(K key)  throws  Exception;
   
     void  destroyObject(K key, PooledObject<V> p)  throws  Exception;
 
     boolean  validateObject(K key, PooledObject<V> p);
    
     void  activateObject(K key, PooledObject<V> p)  throws  Exception;
 
     void  passivateObject(K key, PooledObject<V> p)  throws  Exception;
}

Create object pool  GenericObjectPool

stay org.apache.commons.pool2.impl There are three object pools that can be used directly :GenericObjectPool、GenericKeyedObjectPool and SoftReferenceObjectPool.

Usually use GenericObjectPool To create an object pool , If it's an object pool, it's Keyed Of , Then you can use GenericKeyedObjectPool To create an object pool . Both classes offer rich configuration options . These two object pools are The feature is that you can set the object characteristics in the object pool , Include LIFO( Last in, first out ) The way 、 Maximum free number 、 Minimum number of idle 、 Effectiveness check, etc . The difference between the two is as mentioned above , The latter supports Keyed.

and SoftReferenceObjectPool Object pool , It uses a java.util.ArrayList Object to save the objects in the object pool . But it doesn't store the object itself directly in the object pool , It's about preserving them “ Soft citation ”

(Soft Reference). This object pool features : You can save any number of objects , There won't be a full capacity situation ; When the object pool is empty , Call it the borrowObject Method , The newly created instance is automatically returned ; You can initialize at the same time , Create a certain amount of objects in the pool in advance ; When there's not enough memory , Objects in the pool can be Java Virtual machine recycling .

for instance :

?
1
new  GenericObjectPool<StringBuffer>( new  PooledStringBufferFactory());

We can also use GenericObjectPoolConfig To configure some parameters of the object pool created above , Created Config Parameters , have access to setConfig Method to the object pool , It can also be passed in as a parameter in the construction method of the object pool .

for instance :

?
1
2
3
4
5
GenericObjectPoolConfig conf =  new  GenericObjectPoolConfig();
conf.setMaxTotal( 20 );
conf.setMaxIdle( 10 );
...
GenericObjectPool<StringBuffer> pool =  new  GenericObjectPool<StringBuffer>( new  PooledStringBufferFactory(), conf);

Use object pool

Object pools are easy to use , It's easy to use borrowObject and returnObject Two methods , Let's go straight to the reference code :

borrowObject Part of the code , See the source code for details : Lending pool objects , By creating a new create() Or from idleObjects The pool object is returned in the two terminal queue .idleObjects It's a double ended queue , Save the objects returned to the object pool , Next time you use it, follow LIFO Principles ( Or other principles ) Lending to .

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public  T borrowObject( long  borrowMaxWaitMillis)  throws  Exception {
     PooledObject<T> p =  null ;
 
     while  (p ==  null ) {
         create =  false ;
         if  (blockWhenExhausted) {
             p = idleObjects.pollFirst();
             if  (p ==  null ) {
                 p = create();
                 if  (p !=  null ) {
                     create =  true ;
                 }
             }
             if  (p ==  null ) {
                 if  (borrowMaxWaitMillis <  0 ) {
                     p = idleObjects.takeFirst();
                 else  {
                     p = idleObjects.pollFirst(borrowMaxWaitMillis,
                             TimeUnit.MILLISECONDS);
                 }
             }
             if  (p ==  null ) {
                 throw  new  NoSuchElementException(
                         "Timeout waiting for idle object" );
             }
             if  (!p.allocate()) {
                 p =  null ;
             }
         else  {
             p = idleObjects.pollFirst();
             if  (p ==  null ) {
                 p = create();
                 if  (p !=  null ) {
                     create =  true ;
                 }
             }
         }
     }
     return  p.getObject();
}

returnObject Method , Part of the code , See the source code for details : Returns the pool object , Put in idleObjects Double ended queue save .

Key code :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public  void  returnObject(T obj) {
     PooledObject<T> p = allObjects.get(obj);
 
     int  maxIdleSave = getMaxIdle();
     if  (isClosed() || maxIdleSave > - 1  && maxIdleSave <= idleObjects.size()) {
         try  {
             destroy(p);
         catch  (Exception e) {
             swallowException(e);
         }
     else  {
         if  (getLifo()) {
             idleObjects.addFirst(p);
         else  {
             idleObjects.addLast(p);
         }
     }
     updateStatsReturn(activeTime);
}

It's just a general logic , There's more detail logic control . Like when to destroy , When to create and so on .

==============END==============

commons.pool2 More articles on the use of object pools

  1. JedisCluster The application of Apache Commons Pool Object pool technology

    Object pool technology is widely used in server development . In the implementation of various object pools , Especially the connection pool of database , It can be said that each server must implement the part .   apache common pool Official documents can be referred to :https://c ...

  2. Apache common pool2 Object pool

    Container for object pool : Contains a specified number of objects . When you take an object out of the pool , It doesn't exist in the pool , Until it's put back . Objects in the pool have lifecycles : establish , verification , The destruction , Object pooling helps to better manage available resources , prevent JVM There are a lot of temporary small objects inside , Frequent touch ...

  3. buffer &amp; cache &amp; Understanding the concept of object pool

    One ). buffer effect : Mitigate performance differences between the upper and lower layers of the program . 1). When the performance of the upper component is better than that of the lower component, adding buffer mechanism can reduce the impact of the upper component on the lower component Waiting time for layer components . 2). The upper component does not need to wait for the lower component to receive all the data , You can go back to operation , ...

  4. Java-- Object pooling Technology org.apache.commons.pool2.ObjectPool

    org.apache.commons.pool2.ObjectPool Provides an object pool , Development partners can directly use it to build an object pool There are two simple steps to using this object pool : 1. Create an object factory ,org.apache ...

  5. Object pooling Technology org.apache.commons.pool

    Using object pooling properly , It can effectively reduce the consumption of object generation and initialization , Improve the efficiency of the system .Jakarta Commons Pool Component provides a complete framework for object pooling , And a number of object pool implementations with their own characteristics , Sure ...

  6. Lettuce Connection pool —— solve “MXBean already registered with name org.apache.commons.pool2:type=GenericObjectPool,name=pool”

    LettuceConfig: package com.youdao.outfox.interflow.config; import io.lettuce.core.support.Connection ...

  7. Apache Common-pool2 Object pool analysis and application

    Apache Common-pool2 Package provides a general implementation of object pool technology . It is very convenient to implement its own object pool based on it , such as DBCP and Jedis The implementation of their internal object pool depends on Common-pool2. object ...

  8. Apache Commons Pool2 Source code analysis | Apache Commons Pool2 Source Code Analysis

    Apache Commons Pool The function of object pool is realized . Defines the generation of objects . The destruction . Activate . Passivation and its state transition , It also provides several default object pool implementations . Before describing its implementation principle , First of all, there are several important objects : Pool ...

  9. java Object pool commons-pool-1.6 Detailed explanation ( One )

    I used it in my project Object pool commons-pool: package com.sankuai.qcs.regulation.protocol.client; import com.dianping. ...

Random recommendation

  1. C# Out,Ref Learning summary

    C# Out,Ref Learning summary . ref Is the address where the parameter is passed ,out Is the return value , There are some similarities between them , But there are also differences . Use ref The variable must be assigned a value before ,out no need . out The function of will empty the variable , Even if the variable has been assigned, it is not valid ...

  2. spring Integrate ActiveMQ

    1.1     JMS brief introduction JMS The full name is Java Message Service, namely Java Message service . It's mainly used for messaging between producers and consumers , Producers are responsible for generating messages , The consumer is responsible for receiving the message . Apply it to ...

  3. Line segment tree (main Functional freedom )

    They are all templates of bare line tree , There is no principal function ! #include<cstdio> #include<algorithm> #include<cstring> #include& ...

  4. ShareSDK Third party login code

    - (IBAction)YYSJBut:(UIButton *)sender{    if (sender.tag == 7)    {        [self AuthLogin:SSDKPlat ...

  5. Git Common code management commands

    1) Remote warehouse related commands Check out warehouse :$ git clone git://github.com/jquery/jquery.git View remote repository :$ git remote -v Add remote repository :$ git re ...

  6. open eclipse Report errors : Found the element &#39;d:skin&#39; Invalid content at the beginning . There should be no subelements here .

    [ error ]  open eclipse Report errors : Found the element ‘d:skin’ Invalid content at the beginning . There should be no subelements here . [ Specific error information ] Error parsing D:\Android-sdks\system-im ...

  7. mysql Change user password New users

    Change Password : mysql> grant all privileges on *.* to yongfu_b@'192.168.1.%' identified by 'my_password_new ...

  8. Zookeeper 1、Zookeeper Definition and working principle

    1. What is? Zookeeper » Zookeeper yes Google Of Chubby An open source implementation , yes Hadoop The distributed coordination service » It contains a simple set of primitives , Distributed applications can be synchronized based on it ...

  9. Numbers ( mathematics ) Operation class Math Random class , Big number operation class

    Math Provides a lot of mathematical operations Math All methods in a class are static Method

  10. Use EFI Boot from hard disk (U disc ) install Win7 The picture and text course of

    Currently only supported vista After 64 Bit system Most use EFI Guided installation Win7 All of the tutorials are booted and installed on CD , Although CD-ROM installation is relatively simple , But it's quite inconvenient for friends who don't have an optical drive , Not to mention the two disadvantages of CD-ROM installation , One is slow , Two ...