The principle and implementation of Java object Pool technology

Source: Internet
Author: User

life cycle Analysis of Java objects

The life cycle of a Java object consists of roughly three phases: object creation, object usage, and object cleanup. Therefore, the life cycle length of an object can be expressed in the following expression: T = T1 + T2 +t3. Where T1 represents the object's creation time, T2 represents the object's usage time, and T3 indicates its purge time. Thus, we can see that only T2 is really effective time, while T1, T3 is the cost of the object itself. Let's take a look at the proportions of T1 and T3 throughout the life cycle of the object.

We know that Java objects are created by constructors, and in this process, all constructors in that constructor chain are automatically called. In addition, by default, when invoking the constructor of a class, Java initializes the variable to a certain value: All objects are set to NULL, integer variables (byte, short, int, long) are set to 0, The float and double variables are set to 0.0, and the logical value is set to False. So the time overhead of creating a new object with the New keyword is significant, as shown in table 1.

Table 1 Comparison of time-consuming procedures for some operations

Arithmetic operations Example Standardized time
Locally assigned value i = n 1.0
Instance Assignment value THIS.I = n 1.2
Method invocation Funct () 5.9
New Object New Object () 980
New array New INT[10] 3100

As you can see from table 1, creating a new object takes 980 units of time, is 980 times times the local assignment time, and is 166 times times the method invocation time, and it takes more time to create a new array.

Then look at the process of clearing the object. As we know, one of the advantages of the Java language is that Java programmers do not have to explicitly dispose of objects like C + + programmers, and an automated memory management system called the Garbage Collector (garbage Collector), timed or when memory is not sufficient, Automatically reclaims the memory occupied by garbage objects. There are always pros and cons, although it provides great convenience for Java programmers, but it also brings a large performance overhead. This overhead includes two aspects, first, the object management overhead, in order for the GC to properly dispose of the object, it must monitor the running state of each object, including the application, reference, reference, assignment, etc. of the object. Second, when the GC begins to recycle "garbage" objects, the system pauses the execution of the application and consumes the CPU on its own.

Therefore, if you want to improve the performance of your application, you should minimize the number of times you create new objects, and you should minimize the time of T1 and T3, which can be achieved through object pooling techniques.

   Fundamentals of Object pooling technology

The core of the object pool technology Fundamentals is two: caching and sharing, that is, for those objects that are used frequently, after they are used, they are cached for reuse by subsequent applications, reducing the number of objects and objects that are created and thus improving the performance of the application. In fact, because object pooling technology restricts objects to a certain amount, it also effectively reduces the overhead on application memory.

Implementing an object pool typically involves the following classes:

1) Object Pool Factory (Objectpoolfactory) class

This class is primarily used to manage object pools of the same type and settings (Objectpool), which typically contains the following two methods:

CreatePool: A pool of objects used to create specific types and settings;

Destroypool: Used to release the specified object pool;

At the same time, in order to ensure Objectpoolfactory single instance, can adopt singleton design pattern, see the following getinstance method realization:

public static Objectpoolfactory getinstance () {
if (poolfactory = = null) {
Poolfactory = new Objectpoolfactory ();
}
return poolfactory;
}

2) Parameter object (Parameterobject) class

This class is primarily used to encapsulate some of the property parameters of the created object pool, such as the maximum number of objects that can be held in a pool (maxCount), the minimum value (Mincount), and so on.

3) Object Pool (Objectpool) class

Used to manage the loan and return of objects to be pooled and inform Poolableobjectfactory to complete the work accordingly. It generally consists of the following two methods:

GetObject: Used to borrow objects from a pool;
Returnobject: Returns a pooled object to the pool and notifies all waiting-state threads;

4) Pooled Object Factory (Poolableobjectfactory) class

This class is primarily responsible for managing the life cycle of pooled objects, in simple terms, generally including object creation and destruction. Similar to Objectpoolfactory, it can also be implemented as a single instance.

Implementation of a common object pool

The construction and management of object pools can be implemented in a number of ways. The most flexible way to do this is to specify the class type of the pooled object outside the object pool, that is, when the Objectpoolfactory class creates the object pool, dynamically specifies the class type of the object pooled by the object pool, with the following implementation code:

. . .
Public Objectpool CreatePool (parameterobject paraobj,class clstype) {
return new Objectpool (Paraobj, Clstype);
}
. . .


Where the Paraobj parameter specifies the feature attribute of the object pool, and the Clstype parameter specifies the type of object that the object pool holds. After the object pool (Objectpool) is created, the following is the use of it to manage objects, as follows:

public class Objectpool {
Private Parameterobject paraobj;//Property Parameter object for this object pool
Private Class clstype;//The type of objects that are stored in the object pool
private int currentnum = 0; The number of objects currently created by the object pool
Private object currentobj;//objects that the object pool can currently borrow
Private Vector pool;//a pool for storing objects
Public Objectpool (Parameterobject paraobj, Class clstype) {
This.paraobj = Paraobj;
This.clstype = Clstype;
Pool = new Vector ();
}
Public Object GetObject () {
if (Pool.size () <= Paraobj.getmincount ()) {
if (Currentnum <= paraobj.getmaxcount ()) {
If no objects are available in the current pool and the number of objects created is less than the maximum limit, use
Poolobjectfactory to create a new object
Poolableobjectfactory objfactory =poolableobjectfactory.getinstance ();
CurrentObj = Objfactory.create Object (clstype);
currentnum++;
} else {
If no objects are available in the current pool, and the number of objects created has reached the maximum limit,
You can only wait for other threads to return objects to the pool
Synchronized (this) {
try {
Wait ();
} catch (Interruptedexception e) {
System.out.println (E.getmessage ());
E.printstacktrace ();
}
CurrentObj = Pool.firstelement ();
}
}
} else {
If an object is available in the current pool, the object is fetched directly from the pool
CurrentObj = Pool.firstelement ();
}
return currentobj;
}
public void Returnobject (Object obj) {
Ensure that the object has the correct type
if (Obj.isinstance (Clstype)) {
Pool.addelement (obj);
Synchronized (this) {
Notifyall ();
}
} else {
throw new IllegalArgumentException ("The object pool cannot hold the specified object type");
}
}
}


As can be seen from the above code, Objectpool uses a java.util.Vector as an extensible object pool and uses its constructor to specify the class type of the pooled object and some properties of the object pool. When an object is returned to the object pool, it checks whether the object is of the correct type. When no more objects are available in the object pool, it either waits for the pooled object that has been used to return to the pool, or creates a new object instance. However, the creation of the new object instance is not in the Objectpool class, but is done by the CreateObject method of the Poolableobjectfactory class, which is implemented as follows:

. . .
Public Object CreateObject (Class Clstype) {
Object obj = null;
try {
obj = Clstype.newinstance ();
} catch (Exception e) {
E.printstacktrace ();
}
return obj;
}
. . .


Thus, if the implementation of the Universal object pool is complete, let's look at how the client uses it, assuming the class type of the pooled object is StringBuffer:

...
//Create Object Pool Factory
Objectpoolfactory poolfactory = objectpoolfactory. getinstance ();
Defines the properties of the created object pool
Parameterobject paraobj = new Parameterobject (2,1);
Using the object pool factory, create an object pool that holds StringBuffer type objects
Objectpool pool = poolfactory.createpool (paraobj,string buffer.class);
Remove a StringBuffer object from the pool
stringbuffer buffer = (stringbuffer) pool.getobject ();
Use the StringBuffer object removed from the pool
buffer.append ("Hello");
System.out.println (Buffer.tostring ());  
...

As you can see in


, a common object pool is convenient to use, not only to easily avoid the overhead of creating objects frequently, but also to be highly versatile. Unfortunately, because of the need to use a large number of type-training (cast) operations, coupled with some synchronization of the vector class, it is very limited in some cases to improve performance, especially for those objects with shorter creation cycles.

Implementation of the private object pool

Because of the large administrative overhead of a common object pool, the majority of the benefits of reusing objects are offset to some extent. To solve this problem, you can take a private object pool approach. That is, the class type of the object pool object is not dynamically specified, but is specified beforehand. In this way, it is also simpler to implement than a common object pool, you can not objectpoolfactory and Poolableobjectfactory classes, and their functions are directly fused to the Objectpool class, as follows (assuming that the class type of the pooled object is still stringbuffer, and where the ellipsis is represented, it represents the implementation of the Code with the Common Object pool):

public class Objectpool {
Private Parameterobject paraobj;//The object pool's property parameter object
Private int currentnum = 0;//number of objects currently created by this object pool
Private StringBuffer  currentobj;//The object pool is currently available for borrowing
private Vector pool;//The pool used to hold the object
public Objectpool (Parameterobject paraobj) {
This.paraobj = Paraobj;
Pool = new Vector ();
}
Public StringBuffer getObject () {
if (pool.size () <= Paraobj.getmincount ()) {
if (Currentnum <    = Paraobj.getmaxcount ()) {
CurrentObj = new StringBuffer ();
currentnum++;

...  
}
return currentobj;
}
public void Returnobject (object obj) {
//ensures that the object has the correct type
if (stringbuffer.isinstance (obj)) {
: . 
}
}


  Conclusion

Proper use of object pooling technology can effectively improve application performance. At present, the object pool technology has been widely used, such as for the network and database connections such heavyweight objects, generally will use object pool technology. However, you should also be aware of the following issues when using object pooling techniques:

• Object pooling technology is not a good fit in any situation. Basically, the object pooling technique is only appropriate when the operations that repeatedly generate an object become a key factor in performance. However, if the performance improvement of pooling is not important, it is better not to use the object pooling technique to keep the code concise.

• To correctly select the implementation of the object pool, depending on the situation. Select a Common object pool if you are creating a common object pool technology implementation package, or if you need to dynamically specify the class type of the pooled object in your program. In most cases, it is possible to use a dedicated object pool.

The principle and implementation of Java object Pool technology

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.