Java object pool

Source: Internet
Author: User
Jakarta Object pool

Why use Object pool?

The appropriate use of object Pooling technology can effectively reduce the consumption during object generation and initialization, and improve the system operation efficiency. The Jakarta commons pool component provides a complete set of frameworks for object pooling and several distinctive object pools.

Object pool ideas

The basic idea of object pooling is to save the used objects and use them again when this object is needed for the next time, this reduces the overhead caused by frequent object creation to some extent. The object used as the "Container" for saving objects. It is called the "Object pool" (or "pool" for short ).

For stateless objects (such as string), no processing is required before repeated use; for stateful objects (such as stringbuffer), before repeated use, you need to restore them to the same status as the one just generated. Due to the limitations of the conditions, it is impossible to restore the status of an object, so you have to discard the object and switch to the newly created instance.

Not all objects are suitable for pooling-because maintaining the object pool also causes certain overhead. Pooling objects with low overhead during generation may lead to a situation where the overhead of maintaining the object pool is greater than that of generating new objects, reducing performance. However, for objects with considerable overhead during generation, Pooling technology is an effective strategy to improve performance.

Use object pool

In the pool component, the work of object pooling is divided into three types of objects:

PoolableobjectfactoryUsed to manage the generation, activation, suspension, checksum and destruction of pooled objects;
ObjectpoolUsed to manage the lending and return of objects to be pooled, and notify poolableobjectfactory to complete relevant work;
ObjectpoolfactoryIt is used to generate a large number of objectpools of the same type and settings.
Correspondingly, the process of using the pool component can be roughly divided into three actions: "Creating poolableobjectfactory", "using objectpool", and optional "using objectpoolfactory.

Poolableobjectfactory

Objectpool

Final Structure

Simplify poolableobjectfactory

Poolableobjectfactory defines many methods to adapt to different situations. However, when there is no special need to directly implement the poolableobjectfactory interface, it is complicated to write several methods that do not perform any operations or always return true for compilation. In this case, we can use the power of basepoolableobjectfactory to simplify coding.

Basepoolableobjectfactory is an abstract class in the org. Apache. commons. Pool package. It implements the poolableobjectfactory interface and provides a basic implementation for methods other than makeobject-activateobject, passivateobject, and destroyobject without any operation, while validateobject always returns true. By inheriting this class, instead of directly implementing the poolableobjectfactory interface, you can avoid the trouble of writing some code that can only make compilation pass.

Objectpool implementation class
Stackobjectpool

Stackobjectpool uses a java. util. Stack object to save objects in the object pool. This object pool features:

You can specify an initial reference size for the object pool (it will automatically increase when the space is insufficient ).
When the object pool is empty, the borrowobject method is called and the newly created instance is automatically returned.
You can specify the maximum number of objects that can be saved for the object pool. After this limit is reached, the objects sent back to the pool will be automatically sent for recycling.
Stackobjectpool has six constructor methods, of which:

The simplest one is stackobjectpool (), which uses the default settings and does not specify the poolableobjectfactory instance to be used.
The most complex one is stackobjectpool (poolableobjectfactory factory, int Max, int init ). Where:
The factory parameter specifies the poolableobjectfactory instance to be used;
The max parameter sets the maximum number of objects that can be saved;
The init parameter indicates the initial reference size.
The remaining four constructor methods are the simplified versions of the most complex constructor methods in some aspects, which can be selected as needed. They are:
Stackobjectpool (INT max)
Stackobjectpool (INT Max, int init)
Stackobjectpool (poolableobjectfactory factory)
Stackobjectpool (poolableobjectfactory factory, int max)
A stackobjectpool instance constructed using a constructor without factory parameters must be associated with a poolableobjectfactory instance using its setfactory (poolableobjectfactory) method.

This object pool can run normally without the support of the Jakarta commmons collections component.

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 stores their soft references ). This object pool features:

You can save any number of objects without the full capacity.
When the object pool is empty, the borrowobject method is called and the newly created instance is automatically returned.
You can create a certain number of objects in the pool before initialization.
When the memory is insufficient, the objects in the pool can be recycled by the Java Virtual Machine.
Softreferenceobjectpool has three constructor methods:

The simplest is softreferenceobjectpool (), which does not create objects in the pool in advance or specify the poolableobjectfactory instance to be used.
The most complex one is softreferenceobjectpool (poolableobjectfactory factory, int initsize ). Where:
The factory parameter specifies the poolableobjectfactory instance to be used.
The initsize parameter specifies the number of objects created in the pool during initialization.
The remaining constructor is a simplified version of the most complex constructor in a certain aspect. It is suitable for most cases. It is:
Softreferenceobjectpool (poolableobjectfactory factory)
A softreferenceobjectpool instance constructed using a constructor without the factory parameter must be associated with a poolableobjectfactory instance using its setfactory (poolableobjectfactory) method.

This object pool can also run normally without the support of the Jakarta commmons collections component.

Genericobjectpool

Genericobjectpool uses an org. Apache. commons. Collections. cursorablelinkedlist object to save objects in the object pool. This object pool features:

You can set the maximum number of objects that can be lent out from the pool.
You can set the maximum number of objects that can be saved in the pool.
You can set whether to wait, create a new instance, or throw an exception when no object can be used in the pool to call its borrowobject method.
You can set whether the validity check is performed when the object is lent out or returned.
You can set whether to use a separate thread to clean up objects in the pool in the background.
Genericobjectpool has seven constructor methods, of which:

The simplest one is genericobjectpool (poolableobjectfactory factory ). Only specify the poolableobjectfactory instance to be used, and use the default value for other parameters.
The most complex one is genericobjectpool (poolableobjectfactory factory, int maxactive, byte whenexhaustedaction, long maxwait, int maxidle, Boolean testonborrow, Boolean testonreturn, long wait, int numtestsperevictionrun, long wait, boolean testwhileidle ). Where:
The factory parameter specifies the poolableobjectfactory instance to be used.
The maxactive parameter specifies the maximum number of objects that can be lent out from the pool. If the value is not a positive number, there is no limit.
The whenexhaustedaction parameter specifies the behavior of calling its borrowobject method when the number of Lent objects in the pool has reached the limit. Optional values:
Genericobjectpool. when_exhausted_block, indicating waiting;
Genericobjectpool. when_exhausted_grow indicates creating a new instance (but this makes the maxactive parameter meaningless );
Genericobjectpool. when_exhausted_fail indicates that a java. util. nosuchelementexception exception is thrown.
The maxwait parameter specifies the maximum number of milliseconds to wait if the borrowobject method is called when the object pool is empty. If the wait time exceeds this value, a java. util. nosuchelementexception exception is thrown. If the value is not a positive value, it indicates waiting for an indefinite period.
The testonborrow parameter specifies whether to check the validity of the object when it is lent.
The testonborrow parameter specifies whether to perform a validity check when the object is returned.
The timebetweenevictionrunsmillis parameter sets the interval every several milliseconds for background object cleanup. If this value is not a positive number, the background object will not be cleared.
The numtestsperevictionrun parameter sets the number of objects to be checked each time during background object cleanup. If this value is not a positive number, the number of objects checked each time is the result of multiplying the total number of objects in the pool by the negative reciprocal of the value and then rounded up-that is, if the 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 current pool at a time ......) Left and right.
The minevictableidletimemillis parameter is used to set the object to expire when the background object is cleaned up. Expired objects will be recycled. If this value is not a positive number, there is no special constraint on the sleep time.
The testwhileidle parameter is used to set whether to check the validity of objects in the pool that have not expired during background object cleanup. Objects that cannot pass the validity check will also be recycled.
Another special constructor is genericobjectpool (poolableobjectfactory factory, genericobjectpool. config ). Where:
The factory parameter specifies the poolableobjectfactory instance to be used;
The Config parameter specifies an object that includes the default values of each parameter (for details, see the genericobjectpool. config section ).
The remaining five constructors are the simplified versions of the most complex constructor in some aspect. They can be selected as needed. 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 cannot be run without the support of the Jakarta commmons collections component. [Note] If no parameter value is set, genericobjectpool uses the default parameter value, for example, the maximum number of pools is 8, which may cause an impact.

Genericobjectpool. config

When calling a method with many parameters, it is very likely that the parameter location and number are wrong, resulting in errors during compilation or running; when you read the code that contains a lot of parameters for method calls, it is also possible that you do not have an incorrect understanding of the parameter location and number. Therefore, it is often avoided to assign too many parameters to a method (the so-called "Long Parameter List "). However, some methods require many parameters to complete the work. As a result, some people think of a countermeasure that encapsulates a large number of parameters into an object (called a parameter object), and then uses this object as a single parameter to pass the best of both worlds.

Because the generickeyedobjectpool is generated with many features, many parameters are required in its constructor. In addition to several ultra-long constructor methods, the generickeyedobjectpool also defines a constructor that uses parameter objects. The type of the parameter object used is generickeyedobjectpool. config.

Generickeyedobjectpool. config defines many public fields, each corresponding to a feature 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 serve exactly the same purpose as the parameters with the same name in the most complex constructor of generickeyedobjectpool.

When used, a generickeyedobjectpool. config object is generated, fields are set to the desired value, and the object is used as a unique parameter to call the constructor of generickeyedobjectpool.

Note: A class with many public fields but no methods is often avoided (the so-called "data class "). However, this generickeyedobjectpool is a maverick.

Object pool with key value

Sometimes, an object pool that treats all objects in the pool equally cannot solve the problem. For example, for a group of similar objects with different parameters, such as a bunch of java.net. a URL object or a batch of Java. SQL. the preparedstatement object is pooled using this method, and it may be difficult to retrieve unsuitable objects.

You can create a separate Object pool for similar objects with the same set of parameters to solve this problem. However, if you use a common objectpool to implement this strategy, because the common poolableobjectfactory can only produce a large number of objects with identical settings, you need to write a separate poolableobjectfactory for each set of objects with the same parameters. The workload is considerable. In this case, it is suitable for an "Object pool with a key value" provided by the pool component to expand the work.

The pool component uses classes that implement the keyedobjectpool interface to act as an object pool with a key value. Correspondingly, this object pool needs to be used together with the class that implements the keyedpoolableobjectfactory interface and the class that implements the keyedobjectpoolfactory interface (these three interfaces are all in org. apache. commons. pool package definition ):

The keyedpoolableobjectfactory and poolableobjectfactory formats are exactly the same, but each method adds an object key parameter:
The parameter of makeobject is changed to (Object key)
The activateobject parameter is changed to (Object key, object OBJ)
The parameter of passivateobject is changed to (Object key, object OBJ)
The validateobject parameter is changed to the object key, object OBJ)
The parameter of destroyobject is changed to (Object key, object OBJ)
In addition, the pool component also provides basekeyedpoolableobjectfactory to act as a role similar to basepoolableobjectfactory.

The keyedobjectpool and objectpool formats are similar, but the parameter types of some methods have changed. Some methods are divided into two slightly different versions:
The object borrowobject (Object key) and void returnobject (Object key, object OBJ) are used to take charge of the action of lending and returning objects.
Use void close () to close the object pool that is no longer needed.
Void clear (Object key) and void clear () are used to clear objects in the pool. The former is for instances associated with specific key values, and the latter is for the entire object pool.
Use int getnumactive (Object key) and INT getnumactive () to query the number of borrowed objects. The former is for instances associated with specific key values, and the latter is for the entire object pool.
Use int getnumidle (Object key) and INT getnumidle () to query the number of objects in sleep state. The former is for instances associated with specific key values, and the latter is for the entire object pool.
Use void setfactory (keyedpoolableobjectfactory factory) to set the keyedpoolableobjectfactory instance to be used.
Various versions of void clear, int getnumactive, int getnumidle, and void setfactory can still be determined by the specific implementation. If the keyedobjectpool implementation does not support these operations, an unsupportedoperationexception will be thrown when these methods are called.

Keyedobjectpoolfactory and objectpoolfactory are in the same format, but they represent different objects.

When the amount of lending is less than the return amount

Java does not provide a mechanism to ensure that there is a specific relationship between the number of calls of the two methods (equal, a constant difference, or any other relationship ). Therefore, you can create an objectpool object, call the borrowobject method once, lend an object, and then repeat the returnobject method twice to return the object. Calling the returnobject method of the objectpool that never lent objects is not an incomplete task.

Although these usage methods do not conform to the returnobject literal meaning, the implementation of each objectpool/keyedobjectpool in the pool component does not care about this. Their returnobject methods simply call the poolableobjectfactory instance associated with the current Object pool to see if this object can withstand the test of validateobject. The result of the test determines whether the object should be processed as passivateobject and then reserved for reuse; or should it be processed as a destroyobject to avoid occupying resources. That is to say, when the lending amount is less than the return amount, nothing special happens (of course, it is possible that an exception is thrown because the object pool is in a state that does not accept the return object request, but this is a common phenomenon ).

In actual use, you can use this feature to add objects generated by other methods to the object pool.

When to use the object pool

The purpose of object pooling is to reduce the number of object generation times and reduce the overhead spent on object initialization, thus improving the overall performance. However, pooled processing itself has to pay a price. Therefore, it is not suitable for object pooling in any situation.

Dr. in performance myths exposed, published by Cliff click on javaone 2003, a set of other conditions are given, and the actual performance of using the object Pooling technology is compared. His experimental results show that:

For lightweight objects such as point, after pooled processing, the performance decreases, so it is not appropriate to pooled;

For medium-level objects such as hashtable, after pooled processing, the performance remains basically the same and generally does not need to be pooled (pooling will make the code more complex and increase the difficulty of maintenance );
For heavyweight objects such as jpanel, after pooled processing, the performance has increased and pooling can be considered.
Depending on the method used, the actual situation may be slightly different from the measurement result. On machines with high configurations and virtual machines with strong technology, the range of objects that cannot be pooled may be larger. However, for heavyweight objects such as network and database connections, there is still a need for pooling.

Basically, object pooling is suitable only when repeated object generation is a key factor affecting performance. If the performance improvement caused by pooling is not important, we still do not use the object Pooling technology to keep the code concise, but use better hardware and better virtual machines to improve performance.

Related Article

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.