December 2003
Appropriately use object poolization technology, it can effectively reduce the consumption of object generation and initialization, and improve the operating efficiency of the system. The Jakarta Commons Pool component provides a full set of frameworks for implementing object poolization, as well as several distinctive object pool implementations, can effectively reduce the workload of processing target cells, leaving more important work Energy and time.
Creating a new object and initialize the operation, it may consume a lot of time. In this object of initialization, it includes some time-consuming operations (for example, when some data is read from a host other than 20,000 kilometers), especially. When you need a lot of objects to generate such objects, you may have some non-negligible impact. To alleviate this problem, in addition to selecting better hardware and better virtual machines, it is also an effective countermeasure to properly use some coding techniques that reduce the number of objects to be created. Object Pooling is a famous technique in this area, and Jakarta Commons Pool components are depletion foreign aid for processing object poolization.
The basic idea of the object pool chemical object pool is: saves the objects that have been used. When this object needs this object, it will be reused to a certain extent, reducing the overhead of frequent creating objects. The object used to act as a "container" that saves the object is called "object pool" (Object Pool, or Pool).
For objects (such as String), there is no need to perform any processes before repeated use; for stateful objects (such as StringBuffer), they need to return them to the state when they are just generated. Due to the constraints of the conditions, the operation of restoring an object cannot be implemented, and this object is abandoned and the newly created instance is used.
Not all objects are suitable for pooling - because the maintenance target pool also causes certain overhead. Chili is poolized for objects that are not overwritten during the generation, but may appear "The overhead of the maintenance target pool" is greater than "cost of generating new objects", thereby reducing performance. However, for a significant object, the poolization technology is an effective strategy to improve performance.
Explanation: In addition to "pool", Pool in English, there is also the meaning of "for multi-share resources". The author is very doubtful that the second type is the actual meaning of Pool in "Object Pool", but the "object pool" said that it has been widely circulated, and it is not enough instead of alternative to translation, so this is still use this translation.
JAKARTA Commons Pool Components
Jakarta Commons Pool is a component for implementing object poolization in a Java program. Its basic situation is:
Main author: Morgan Delagrange, Geir Magnusson, Craig McClanahan, Rodney Waldhoff, David Weinrich and Dirk Verbeeck latest version: 1.1 Number of packages contained: 2 (org.apache.commons.pool and org.apache.commons.pool.impl) Number of categories: 21 (4 abstractions and 6 interfaces) Applicable platform: Java 2, Standard Edition. Simply use the Pool Components without much Java 2 knowledge and experience, grammar and basic concept (Objects, exceptions, classes, interfaces, instances, inheritance and implementation, etc.) have a general understanding.
Download and Install To successfully use the POOL component in accordance with the methods mentioned herein, remove the Java 2 SDK, you need to prepare the following things first: Jakarta Commons Pool
Required version: 1.0.1 Download Address: http://jakarta.apache.org/commons/pool effect: Processing Objects Chihua Jakarta Commons Collectes
Required version: 2.1 Download Address: http://jakarta.apache.org/commons/collections Run: Support Jakarta Commons Pool
The above two software have two forms of compiled packages and source code packages. In general, use the compiled package. However, it is recommended to download the source code package as a reference material.
If you plan to use the source package yourself, you need to prepare something below:
Ant
Required version: 1.5.3 Download Address: http://ant.apache.org Role: Run Compilation Script JUnit
Required version: 3.8.1 Downloads: http://www.junit.org Role: Compile and run unit test
Specific compilation methods, you can see the relevant ANT documentation.
The commons-pool. Jar and Commons-Collections.jar obtained after decompression or compile will be placed in ClassPath, and you can start using the Pool component.
PoolableObjectFactory, ObjectPool, and ObjectPoolFactory In the pool component, the work of the object pool is divided into three types of objects:
PoolableObjectFactory is used to manage the generation, activation, hang, checkiga destruction of the poolized object; ObjectPool is used to manage the borrowing and return of objects to be poolized, and inform PoolableObjectFactory to complete the work; ObjectPoolFactory is used for A large amount of ObjectPool generates the same type and setting.
Accordingly, the process of using the pool component is also generally divided into "founding PoolableObjectFactory", "using ObjectPool" and optionally "using ObjectPoolFactory".
Create a PoolableObjectFactory pool component to take advantage of PoolBjectFactory to look at the pool. ObjectPool's instances are operable to operate the corresponding method of the PoolableObjectFactory instance that is associated with the PoolleObjectFactory instance that needs to be processed by the pool.
PoolableObjectFactory is an interface defined in the org.apache.commons.pool package. A specific implementation of this interface is required when actually use. The pool component itself does not contain any PoolableObjectFactory implementation, and needs to be created according to the situation.
The general step of creating PoolableObjectFactory is:
Create a class that implements the PoolableObjectFactory interface.
Import org.apache.commons.pool.poolableObjectFactory;
Public Class PoolableObjectFactorySample
Implements poolableObjectFactory {
Private statin = 0;
}
Add an Object makeObject () method to this class. This method is used to generate new objects when necessary.
Public Object makeObject () throws exception {object obj = string.valueof (counter );
System.err.Println ("Making Object" Obj);
Return Obj;
}
Add a Void ActivateObject (Object Obj) method for this class. This method is used to set the object "activation"-set the status suitable for starting.
Public void ActivateObject (Object obj) throws exception {
System.err.Println ("Activating Object" Obj);
}
Add a Void PassivateObject (Object Obj) method for this class. This method is used to set the object "hang" - set to the state of the sleep.
Public void passivateObject (Object obj) throws exception {
System.err.Println ("Passivating Object" Obj);
}
Add a Boolean ValidateObject (Object Obj) method for this class. This method is used to verify that a specific object is still valid, and the object that has been invalid will be automatically handed over to the destroyObject method.
Public Boolean ValidateObject (Object Obj) {
Boolean Result = (Math.random ()> 0.5);
System.err.Println ("Validating Object"
Obj ":" result);
Return Result;
}
Add a Void DestroyObject (Object Obj) method for this class. This method is used to destroy objects that are determined by the validateObject as the failure.
Public void destroyObject (Object obj) throws exception {
System.err.Println ("Destroying Object" Obj);
}
The last completed poolaableObjectFactory is like this:
PoolableObjectFactorySample.JAVA
Import org.apache.commons.pool.poolableObjectFactory;
Public Class PoolableObjectFactorySample
Implements poolableObjectFactory {
Private statin = 0;
Public Object makeObject () throws exception {
Object obj = String.Valueof (counter );
System.err.Println ("Making Object" Obj);
Return Obj;
}
Public void ActivateObject (Object obj) throws exception {
System.err.Println ("Activating Object" Obj);
}
Public void passivateObject (Object obj) throws exception {
System.err.Println ("Passivating Object" Obj);
}
Public Boolean ValidateObject (Object Obj) {/ * determines the object to be invalid at 1/2 of the probability * /
Boolean Result = (Math.random ()> 0.5);
System.err.Println ("Validating Object"
Obj ":" result);
Return Result;
}
Public void destroyObject (Object obj) throws exception {
System.err.Println ("Destroying Object" Obj);
}
}
After using ObjectPool With the right poolaableObjectFactory, you can start with the ObjectPool to perform with the same stage.
ObjectPool is an interface defined in the org.apache.commons.pool package. A specific implementation of this interface is also required when actually used. The POOL component itself contains several ready-made ObjectPool implementations, which can be used directly. If it is not used, you can also create it according to the situation. Specific creation methods, you can see the documentation and source code for the Pool component.
How to use ObjectPool is like this:
Generate an instance of a PoolableObjectFactory class you want to use.
PoolableObjectFactory Factory = New poolaableObjectFactorySample ();
With this PoolableObjectFactory instance as a parameter, an instance of a class that implements the ObjectPool interface, as the object pool.
ObjectPool Pool = New StackObjectPool (Factory);
When the object is required from the object pool, the object borrowobject () method of the object pool is called.
Object obj = NULL;
Obj = pool.borrowObject ();
The Void ReturnObject (Object Obj) method of the object pool is called when the object is placed back into the object pool.
Pool.ReturnObject (OBJ);
When you no longer need to use an object pool, call the void close () method of the object pool to release the resources it occupied.
Pool.Close ();
These operations may throw an exception and need additional processing.
Compare the full process of ObjectPool, you can refer to this code:
ObjectPoolsample.java
Import org.apache.commons.pool.Objectpool;
Import org.apache.commons.pool.poolableObjectFactory;
Import org.apache.commons.pool.impla.stackObjectPool;
Public class ObjectPoolsample {
Public static void main (String [] args) {
Object obj = NULL;
POOLABLEOBJECTFACTORY FACTORY
= New poolableObjectFactorySample ();
ObjectPool Pool = New StackObjectPool (Factory);
Try {
FOR (long i = 0; i <100; i ) {
System.out.println ("==" i "==); obj = pool.borrowObject ();
System.out.println (OBJ);
Pool.ReturnObject (OBJ);
}
Obj = null; // Clearly set to null, as a sign that the object has been returned
}
Catch (Exception E) {
E.PrintStackTrace ();
}
Finally {
Try {
IF (Obj! = null) {// Avoid returning one object twice
Pool.ReturnObject (OBJ);
}
Pool.Close ();
}
Catch (Exception E) {
E.PrintStackTrace ();
}
}
}
}
In addition, the ObjectPool interface also defines several operations that can be determined by specific implementation, including:
void clear ()
Clear all the objects that are currently sleeping in this object pool.
Int getnumactive ()
Returns the total number of objects that have been borrowed from this object pool.
Int getnumidle ()
Returns the number of objects that currently sleep in this object pool.
Void SetFactory (PoolableObjectFactory Factory)
Associate the current object pool with the PoolableObjectFactory given in the parameters. If this is not completed in the current state, there will be an IllegalStateException exception thrown. If the ObjectPool implementation does not support these operations, then a unsupportedOperationException exception is thrown when these methods are called.
With ObjectPoolFactory sometimes, you want to generate types and settings in multiple places. If you rewrite the code of the corresponding constructor once in each place, it is not only troublesome, but also in the future, it is inconvenient. This time is the timing of using ObjectPoolFactory.
ObjectPoolFactory is an interface defined in org.apache.commons.pool, which defines a use ObjectPool CreatePool () method that can be used for large quantities of production types and settings.
In the POOL component, each ObjectPool implementation has a corresponding ObjectPoolFactory implementation. They have the same constructor with one one one one. When using, just use an ObjectPoolFactory object with the desired parameters and the ObjectPoolFactory instance you want, and then call this object's CreatePool () method. In the future, no matter whether you want to adjust the parameters used or type, you only need to modify this, you can tell you.
The example in the "Use ObjectPool" section is changed to generate the ObjectPool object used by ObjectPoolFactory, which is basically this form:
ObjectPoolFactorySample.java
Import org.apache.commons.pool.Objectpool;
Import org.apache.commons.pool.ObjectPoolfactory;
Import org.apache.commons.pool.poolableObjectFactory;
Import org.apache.commons.pool.Impl.stackObjectPoolFactory; Public Class ObjectPoolFactorySampleSample {
Public static void main (String [] args) {
Object obj = NULL;
POOLABLEOBJECTFACTORY FACTORY
= New poolableObjectFactorySample ();
ObjectPoolFactory poolfactory
= New StackObjectPoolFactory (Factory);
ObjectPool pool = poolfactory.createpool ();
Try {
FOR (long i = 0; i <100; i ) {
System.out.println ("==" i "==");
Obj = pool.borrowObject ();
System.out.println (OBJ);
Pool.ReturnObject (OBJ);
}
Obj = NULL;
}
Catch (Exception E) {
E.PrintStackTrace ();
}
Finally {
Try {
IF (Obj! = null) {
Pool.ReturnObject (OBJ);
}
Pool.Close ();
}
Catch (Exception E) {
E.PrintStackTrace ();
}
}
}
}
Many methods are defined by using BasepooLableObjectFactory poolaableObjectFactory to accommodate a variety of different situations. However, when there is nothing special needs, directly implement the POOLABLEOBJECTFACTORY interface, you must write a number of methods that do not perform any operation, or always return TRUE to make compilation pass, more cumbersome. This time you can simplify the coding work with the power of BasepoolableObjectFactory.
BasepooLableObjectFactory is an abstract class in the org.apache.commons.pool package. It implements the PoolableObjectFactory interface, and provides a basic implementation in addition to MakeObject ,ActivateObject, PassivateObject, and DestroyObject do not perform any operation, and ValidateObject always returns true. By inheriting this class, instead of directly implementing the POOLABLEOBJECTFACTORY interface, you can freely write some code that only makes compilation.
This example shows a PoolableObjectFactory extended from BasepooLableObjectFactory:
BasepoolableObjectFactorySample.java
Import org.apache.commons.pool.basepoolableObjectFactory;
Public Class BasepoolableObjectFactorySample
Extends basepoolableObjectFactory {
Private int counter = 0;
Public Object makeObject () throws exception {
Return String.Valueof (Counter );
}
}
A wide variety of ObjectPool Coca-Cola's soft drinks have varieties such as Coca-Cola, Sprite and Fanta. Pepsi company's soft drink has a type of Pepsi, Seven Happiness and USA, and the ObjectPool implementation provided by the Pool component has StackObjectPool, SoftReferenceObjectPool and GenericObjectPool. . Different types of soft drinks have their own characteristics, respectively adapt to different consumer tastes; different types of ObjectPool also have their own characteristics, respectively adapt to different situations.
StackObjectPool StackObjectPool uses a Java.util.stack object to save objects in the object pool. The features of this object pool are:
You can specify an initial reference size for the object pool (automatically grow when space is not enough). When the object pool is already empty, the BorrowObject method that calls it will automatically return to the newly created instance. A upper limit of the number of objects that can be saved can be specified for the object pool. After reaching this upper limit, the object sent back to the pool will be automatically sent.
There are six construction methods of StackObjectPool, of which:
The simplest is StackObjectPool (), everything uses the default setting, nor does it specify the PoolableObjectFactory instance you want to use. The most complex one is StackObjectPool (PoolableObjectFactory Factory, Int Max, Int init. among them:
Parameter Factory specifies the PoolableObjectFactory instance to be used with it; the parameter MAX setting can save the upper limit of the number of objects; the parameter init indicates the initial reference size. The remaining four constructors are the most complex constructor's simplified version of a certain aspect, and can be selected as needed. They are:
StackObjectPool (int MAX) StackObjectPool (int Max, int init) stackObjectpool (PoolableObjectFactory Factory) StackObjectPool (PoolableObjectFactory Factory, Int Max)
STACKOBJECTPOOL instances constructed with constructors without a Factory parameter, you must use its setFactory (PoolableObjectFactory Factory method to associate with a POOLABLEOBJECTFAActory instance before you can use it.
This object pool can run normally without Jakarta CommMons Collectes component support.
SoftReferenceObjectPool SoftReferenceObjectPool uses a Java.util.ArrayList object to save objects in the object pool. However, it does not directly save the object itself in the object pool, but to save their "soft reference". The features of this object pool are:
You can save any multiple objects, and there is no capacity that is full. When the object pool is already empty, the BorrowObject method that calls it will automatically return to the newly created instance. It can be initialized, and a certain amount of object is created in advance in the pool. When memory is insufficient, the object in the pool can be reclaimed by Java virtual machines.
SoftReferenceObjectPool has three construction methods, including:
The simplest is SOFTREFERENCEOBJECTPOOL (), which is not pre-created in the pool, nor does it specify the PoolableObjectFactory instance you want to use. The most complex one is SoftReferenceObjectPool (PoolableObjectFactory Factory, Int InIitsize). Where: Parameter Factory indicates how many objects created in the pool when the PoolableObjectFactory instance parameter INITSE to be used in conjunction with it. The remaining construction method is the most complex structure method in a simplified version of a certain aspect, suitable for use in most cases. it is:
SoftReferenceObjectPool (PoolableObjectFactory Factory)
SoftReferenceObjectPool instances constructed with constructors without a Factory parameter, but also to use its setFactory (PoolableObjectFactory Factory method to associate with a PoolableObjectFactory instance can be used normally.
This object pool can also run normally without Jakarta CommMons Collections component support.
GenericObjectPool GenericObjectPool uses an org.apache.commons.collections.cursorablelinkedList object to save objects in the object pool. The features of this object pool are:
You can set up to how many objects can be borrowed from the pool. You can set up to how many objects can be saved in the pool. It can be set in the case where there is no object that can be borrowed in the pool, and the behavior when it calls its BorrowObject method is waiting, create a new instance or throw an exception. You can set a validity check when you set an object borrowing and returning. You can set whether or not a separate thread is used, and the inside object is used to clean up.
The construction method of GenericObjectPool has seven, of which:
The simplest one is genericObjectPool (PoolableObjectFactory Factory). Simply specifically indicate the PoolableObjectFactory instance you want, and other parameters use the default value. The most complex one is GenericObjectPool (PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn, long timeBetweenEvictionRunsMillis, int numTestsPerEvictionRun, long minEvictableIdleTimeMillis, boolean testWhileIdle). among them:
Parameter Factory indicates the PoolableObjectFactory instance to be used with it. The parameter MAXACTIVE indicates the maximum number of objects that can be borrowed from the pool. If this value is not a positive, there is no limit. The parameter WHENEXHAUSTEDACTION specifies the behavior when the BorrowObject method is called when the number of borrowed objects is reached. The values that can be selected are:
GenericObjectPool.WHEN_EXHAUSTED_BLOCK, represents the wait; GenericObjectPool.WHEN_EXHAUSTED_GROW, represents the creation of a new instance (but which makes maxActive parameter loses its meaning); GenericObjectPool.WHEN_EXHAUSTED_FAIL, represents a java.util.NoSuchElementException throws an exception. Parameters MaxWait indicate how many milliseconds are waiting for the behavior of calling the BorrowObject method when the object pool is empty. If the wait time exceeds this value, a java.util.nosuchelementexception exception will be thrown. If this value is not a positive number, it means an indefinite waiting. Parameter Testonborrow is set to check if the object is valid. The parameter Testonborrow is set to check if the object is also valid. The parameter TIMEBEENEENEVISMILLIS, the setting interval is a mobility of a background object cleaning every time. If this value is not a positive number, it does not actually clean up the background object. Parameter NumTestSpeRevictionRun, setting several objects each time when the background object is cleaned up. If this value is not a positive number, the number of objects per check is the result of the total number of inside the pool to take the result of the negative count of this value. That is, if this value is -2 (-3, -4, -5 ...), then check about 1/2 (1/3, 1/4, 1/5 ...) of the total number of objects in the pool each time. The parameter MineVictableIdletimeMilliis is set when the background object is cleaned up, and the sleep time exceeds how many milliseconds of the object is expired. Expired objects will be recycled. If this value is not a positive number, there is no special constraint for sleep times. The parameter TestWhileIdle is set to perform a validity check if there is no expired pool object when the background object is cleaned. Objects that cannot be checked by validity will also be recycled. Another relatively special construction method is GenericObjectPool (PoolableObjectFactory Factory, GenericObjectPool.config Config). Where: Parameter Factory indicates the PoolableObjectFactory instance to be used in conjunction with it; the parameter config indicates an object that includes a preset value of each parameter (see "GenericObjectPool.config" section). The remaining five constructors are the most complex constructor in a simplified version of a certain aspect, which can be selected according to the situation. They are:
GenericObjectPool (PoolableObjectFactory factory, int maxActive) GenericObjectPool (PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait) GenericObjectPool (PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, boolean testOnBorrow, boolean testOnReturn) GenericObjectPool (PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle) GenericObjectPool (PoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, boolean testOnBorrow, boolean testOnReturn) this object pool can not run without the support assembly Jakarta Commmons Collections situation.
GenericObjectPool.config When there is a lot of methods with a lot of parameters, it is likely that the location of the parameters and the number of numbers will be wrong, causing errors in compilation or runtime; reading the code containing a lot of parameters, is also very It may cause an error-friendly understanding because there is no position and number of parameters. Therefore, people tend to avoid a way to arrange too many parameters (so-called "long parameter list"). However, some methods do need a lot of parameters to do work. As a result, some people think of a large number of parameters into an object (called parameter object, parameter object), and then the object as a single parameter to pass the two full parameters.
Because the characteristics of the settings available when generating generickeyedObjectPool, there is a lot of parameters in its constructor. In addition to providing several long constructor, GenericKeYedObjectPool also defines a construction method using parameter objects. The type of parameter object used is GenericKeyedObjectPool.config.
GenericKeYedObjectPool.config defines a lot of public fields, each corresponding to the features that can be set for generickeyedObjectPool, including:
int maxActive int maxIdle long maxWait long minEvictableIdleTimeMillis int numTestsPerEvictionRun boolean testOnBorrow boolean testOnReturn boolean testWhileIdle long timeBetweenEvictionRunsMillis byte whenExhaustedAction
These fields are identical to the parameters of the same name in GenericKeyedObjectPool.
When used, Mr. generickeyedObjectPool.config, then set a field to the desired value, and finally use this object as the unique parameter to call the generickeyedObjectPool constructor.
Note: Use a number of public fields, but there is no way to use, it is also a behavior that people tend to avoid (so-called "Data Class"). However, this time GenericKeyedObjectPool is standing alone. The key-value object pool is sometimes used in the same way with all objects in the pool, and does not solve the problem. For example, for a group of certain parameters set different similar objects - such as a plurality of java.net.URL objects pointing to different addresses or a batch of java.sql.preparedStateMent objects representing different statements, in such ways, It is possible to take out the trouble of the subject.
This issue can be established by establishing a separate object pool to establish a separate object pool for each set of parameters. However, if you use ordinary ObjectPool to implement this policy, because ordinary PoolableObjectFactory can only produce a large number of sets of fully consistent objects, you need to write a separate PoolableObjectFactory for each group of parameters, and the workload is quite considerable. This time is suitable for the field of "key-value object pool" provided in the Pool component to start working.
The pool component uses classes that implement the KeyedObjectPool interface, to act as a key-to-key-valued object pool. Correspondingly, this object pool needs to cooperate with the class of the KeyedPooBleObjectFactory interface and the class that implements the KeyedObjectPoolFactory interface (these three interfaces are defined in the org.apache.commons.pool package):
KeyedPooLableObjectFactory and poolaableObjectFactory forms, but each method has added an Object Key parameter:
makeObject parameters become parameters (Object key) activateObject changed parameters (Object key, Object obj) passivateObject changed parameters (Object key, Object obj) validateObject becomes Object key, parameter Object obj) destroyObject becomes ( Object Key, Object OBJ) Another Pool component also provides BaseKeyedPooLableObjectFactory for acting as a similar role in the and BasepooLableObjectFactory. The form of KeyedObjectPool and ObjectPool is similar, but the parameter type of certain methods has changed, and some methods are divided into two slightly different versions:
Use Object BorrowObject (Object Key) and Void ReturnObject (Object Key, Object Obj) to be responsible for the action of object borrowing and return. Use void close () to close the non-needed object pool. Use Void Clear (Object Key) and Void Clear () to empty the objects in the pool, the former for the instance associated with a specific key value, the latter for the entire object pool. Query the number of objects that have been borrowed with int GETNUMACTIVE (Object Key) and int GETNUMACTIVE (). The former is for the entire object pool for the instance associated with a specific key value. Query the number of objects in sleeping with int GETNUMIDLE (), and int GETNumIdle (), the former is for the entire object pool for the instance associated with a particular key value. Set the KeyedPooLableObjectFactory instance you want to use with Void SetFactory (KeyedPooLableObjectFactory Factory. Void Clear, Int getnumactive, all versions of the int GetNumIdle and Void SetFactory can still be determined by the specific implementation of whether or not to support. If the keyedObjectPool implementation does not support these operations, you will throw a unsupportedOperationException exception when calling these methods. The form of KeyedObjectPoolFactory and ObjectPoolFactory is exactly the same, just that the object represented is different. The basic method of use of this type of object pool is close to this:
KeyedObjectPoolsample.JAVA
Import org.apache.commons.pool.basekeyedpooLableObjectFactory;
Import org.apache.commons.pool.keyedObjectPool;
Import org.apache.commons.pool.keyedObjectPoolFactory;
Import org.apache.commons.pool.keyedpooLableObjectFactory;
Import org.apache.commons.pool.impla.stackKeyedObjectPoolFactory;
Class KeyedPoolableObjectFactorySample
Extends basekeyedpooLableObjectFactory {
Public Object MakeObject (Object Key) throws Exception {
Return New String ("[" key.hashcode () "]");
}
}
Public class keyedObjectPoolsample {
Public static void main (String [] args) {
Object obj = NULL;
KeyedPoolableObjectFactory Factory
= New KeyedPooLableObjectFactorySample ();
KeyedObjectPoolFactory poolfactory
= New StackKeyedObjectPoolFactory (Factory);
KeyedObjectPool pool = poolfactory.createpool ();
String key = NULL;
Try {
FOR (long i = 0; i <100; i ) {
Key = "" (int) (math.random () * 10); system.out.println ("==" i "==");
System.out.println ("Key:" key);
Obj = pool.borrowObject (key);
System.out.println ("Object:" OBJ);
Pool.ReturnObject (key, obj);
Obj = NULL;
}
}
Catch (Exception E) {
E.PrintStackTrace ();
}
Finally {
Try {
IF (Obj! = null) {
Pool.ReturnObject (key, obj);
}
Pool.Close ();
}
Catch (Exception E) {
E.PrintStackTrace ();
}
}
}
}
There are two types of KeyedObjectPool and generickeyedObjectPool and generickeyedObjectPool and GenericKeedObjectPool. Their use methods are basically consistent with their respective close relatives keyedObjectPool and KeyedObjectPool, just where genericObjectPool.config is used to use genericKeYedObjectPool.config.
A specific relationship is presented between the two methods being called by the two methods (equal, different constants, or any other relationship). Therefore, it is possible to create an ObjectPool object, then call a BorrowObject method, borrow an object, then repeat twice ReturnObject method calls, twice return. Calling an ObjectPool approach from an ObjectPool that has never led an object is not a unfinable task.
Although these methods do not match the literal meaning of ReturnObject, the various ObjectPool / KeyedObjectPool implementations in the pool component do not care about this. They only summon the PoolableObjectFactory instance associated with the current object pool to see if this object can be tested by ValidateObject. The results of the test determine that this object should take it to passivateObject processing, and then leave reuse; or should take DESTROYOBJECT processing to avoid occupying resources. That is, when it is returned, there will be no extra special things (of course, it may throw an abnormality because the object pool is in the state of the request to return the target, but this is a conventional phenomenon) .
In actual use, this feature can be utilized to add objects generated by other methods to the object pool.
Thread security issues sometimes need to use the pool components in a multi-threaded environment, which will encounter problems associated with thread safety of the Pool component.
Because ObjectPool and KeyedObjectPool are interfaces defined in org.apache.commons.pool, it is not possible to use "synchronized" in the interface, so that the various methods under an objectpool / keyedObjectPool are synchronous methods, completely Specific implementation. Moreover, the synchronization method is simply used, and the object is not allowed to be in a multi-threaded environment.
In terms of the implementation of several ObjectPool / KeyedObjectPools comes with the Pool components, they all take into account the cases used in multi-threaded environments. But can't say they are complete "thread safety". For example, this code sometimes has some strange performance, and the result of the last output is larger than expected:
UnsafeMultithreadPoolingsample.java
Import org.apache.commons.pool.Objectpool;
Import org.apache.commons.pool.impla.stackObjectPool;
Class unsafepicker extends thread {
Private ObjectPool POOL;
Public unsafepicker (ObjectPool OP) {
POOL = OP;
}
Public void run () {
Object obj = NULL;
Try {
/ * Seems ... * /
IF (pool.getnumactive () <5) {
Sleep ((long) (Math.random () * 10));
Obj = pool.borrowObject ();
}
}
Catch (Exception E) {
E.PrintStackTrace ();
}
}
}
Public class unsafemultithreadpoolingsample {
Public static void main (String [] args) {
Objectpool pool = new stackObjectpool
New BasepooLableObjectFactorySample ());
Thread TS [] = new thread [20];
For (int J = 0; j TS [J] = New UnsafePicker (Pool); TS [J] .Start (); } Try { Thread.sleep (1000); / * However ... * / System.out.println ("Numactive:" pool.getnumactive ()); } Catch (Exception E) { E.PrintStackTrace (); } } } To avoid this, we must further take some measures: SafeMultithreadPoolingsample.java Import org.apache.commons.pool.Objectpool; Import org.apache.commons.pool.impla.stackObjectPool; Class SafePicker Extends thread { Private ObjectPool POOL; Public SafePicker (ObjectPool OP) { POOL = OP; } Public void run () { Object obj = NULL; Try { / * 加 处理 * / SYNCHRONIZED (POOL) { IF (pool.getnumactive () <5) { Sleep ((long) (Math.random () * 10)); Obj = pool.borrowObject (); } } } Catch (Exception E) { E.PrintStackTrace (); } } } Public class safemultithreadpoolingsample { Public static void main (string [] args) {ObjectPool pool = new StackObjectPool New BasepooLableObjectFactorySample ()); Thread TS [] = new thread [20]; For (int J = 0; j TS [J] = New SafePicker (Pool); TS [J] .Start (); } Try { Thread.sleep (1000); System.out.println ("Numactive:" pool.getnumactive ()); } Catch (Exception E) { E.PrintStackTrace (); } } } Basically, it can be said that the POOL component is a thread. But to use in multi-threaded environments, you need to do some special processing. When do you want to use objects to use objects, it is to reduce the overall performance by reducing the number of objects generated by reducing objects, thereby increasing overall performance. However, the poolization processing itself should also pay the price, and therefore, it is not suitable for use with object cells. Dr. Cliff Click Published in "Performance Myths Exposed" in Javaone 2003, a comparison of the actual performance of the actual performance of the object pool is given in the "Performance Myths Exposed" published on Javaone 2003. His measured results show that: For a lightweight object similar to POINT, the performance will decrease, so it is not advisory; for medium-level objects like HashTable, the performance is basically unchanged, and the performance is basically not necessary to poolize (Pihua will make the code become complex, increase the difficulty of maintenance); for a heavyweight object like JPANEL, the performance has risen, and the pool is considered. According to the method of use, the actual situation may be slightly available with this measurement result. On the virtual machine with high machines and technologies, the range of non-pool-free objects may be larger. However, for objects such as networks and databases, there is still a need for poolization. Basically, the object pool is appropriate when the operation of repeating the operation of a certain object is a key factor affecting performance. If the performance of the pool can be improved, it is not important, or the object pool technology is not used to maintain the conciseness of the code, and the performance of better hardware and better virtual machines can be improved. Conclusion The object pool is properly used, which can effectively reduce the overhead that frequently generates some objects, thereby increasing the overall performance. With Jakarta Commons Pool components, it can effectively reduce the workload of the treated object cells, thereby investing more time and effort to other important work. Reference