Java object pool example

Source: Internet
Author: User

The basic idea of using the object pool 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. 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. The following is an example of building an object pool:

 Public   Class Objectpool {
Private Int Numobjects = 10; // Object pool size
Private Int Maxobjects = 50; // Maximum Object pool size
Private Vector objects = Null ; // Stores the vector of objects in the object pool (pooledobject type)

Public Objectpool (){
}

/** * Create an object pool ** */
Public Synchronized Void Createpool (){
// Make sure that the object pool is not created. If the object is created, the object's vector objects will not be empty.
If (Objects! = Null ){
Return ; // If it has been created, return
}

// Creates a vector that saves objects. At first, there are 0 elements.
Objects =New Vector ();

// Create a specified number of objects cyclically based on the value set in numobjects
For ( Int X = 0; x <numobjects; X ++ ){
If (Objects. Size () = 0 )&& This . Objects. Size () < This . Maxobjects ){
Object OBJ = New OBJ ();
Objects. addelement (New Pooledobject (OBJ ));
}
}
}

Public Synchronized Object GetObject (){
// Make sure the object pool has been created
If (Objects = Null ){
Return Null ; // If the object pool has not been created, null is returned.
}

Object conn = getfreeobject (); // Obtain an available object

// If no object can be used currently, that is, all objects are in use.
While (Conn = Null ){
Wait (250 );
Conn = getfreeobject (); // Try again until available objects are obtained. If
// If the return value of getfreeobject () is null, the available objects cannot be obtained after a batch of objects are created.
}

Return Conn; // Returns available objects.
}

/**
* This function returns an available object from the object pool objects. If
* If no available objects exist, create several objects and put them in the object pool.
* If all objects are in use after creation, null is returned.
*/
Private Object getfreeobject (){

// Obtain an available object from the object pool
Object OBJ = findfreeobject ();

If (OBJ = Null ){
Createobjects (incrementalobjects ); // If no available objects exist in the current Object pool, create some objects

// Review available objects from the pool
OBJ = findfreeobject ();

// If no available object is available after the object is created, null is returned.
If (OBJ = Null ){
Return Null ;
}
}

Return OBJ;
}

/**
* Search for all objects in the object pool and find an available object,
* If no available object exists, null is returned.
*/
Private Object findfreeobject (){

Object OBJ = Null ;
Pooledobject pobj = Null ;

// Obtain all objects in the object pool vector.
Enumeration enumerate = objects. Elements ();

// Traverse all objects to see if any objects are available
While (Enumerate. hasmoreelements ()){
Pobj = (pooledobject) enumerate. nextelement ();

// If this object is not busy, obtain its object and set it to busy
If (! Pobj. isbusy ()){
OBJ = pobj. GetObject ();
Pobj. setbusy ( True );
}

Return OBJ; // Returns the available objects found.
}


/**
* This function returns an object to the object pool and sets this object to idle.
* All objects obtained using the object pool should be returned if this object is not used.
*/

Public Void Returnobject (Object OBJ ){

// Make sure that the object pool exists. if the object is not created (does not exist), return directly
If (Objects =Null ){
Return ;
}

Pooledobject pobj = Null ;

Enumeration enumerate = objects. Elements ();

// Traverse all objects in the object pool and find the object to be returned.
While (Enumerate. hasmoreelements ()){
Pobj = (pooledobject) enumerate. nextelement ();

// First, find the object to be returned in the object pool.
If (OBJ = pobj. GetObject ()){
// Found, set this object to idle
Pobj. setbusy ( False );
Break ;
}
}
}


/**
* Close all objects in the object pool and clear the object pool.
*/
Public Synchronized Void Closeobjectpool (){

// Make sure the object pool exists. If not, return
If (Objects = Null ){
Return ;
}

Pooledobject pobj =Null ;

Enumeration enumerate = objects. Elements ();

While (Enumerate. hasmoreelements ()){

Pobj = (pooledobject) enumerate. nextelement ();

// If you are busy, wait for 5 seconds.
If (Pobj. isbusy ()){
Wait (5000 ); // Wait 5 seconds
}

// Delete it from the object pool Vector
Objects. removeelement (pobj );
}

// Empty Object pool
Objects = Null ;
}


/**
* EnableProgramWait for the specified number of milliseconds
*/
Private Void Wait ( Int Mseconds ){
Try {
Thread. Sleep (mseconds );
}
Catch (Interruptedexception e ){
}
}


/**
* Classes used internally to save objects in the object pool.
* This class has two members, one being an object, and the other being a flag indicating whether the object is in use.
*/
Class Pooledobject {

Object objection = Null ; // Object
Boolean Busy = False ; // Indicates whether the object is in use. It is not in use by default.

// Construct a pooledobject object based on an object.
Public Pooledobject (Object objection ){

This . Objection = objection;

}

// Returns the objects in this object.
Public Object GetObject (){
Return Objection;
}

// Set the object.
Public Void Setobject (Object objection ){
This . Objection = objection;

}

// Get whether the object is busy
Public Boolean Isbusy (){
Return Busy;
}

// Setting the object is busy
Public Void Setbusy ( Boolean Busy ){
This . Busy = busy;
}
}
}


Test class:
Code As follows:

Public Class Objectpooltest {
Public Static Void Main (string [] ARGs) Throws Exception {
Objectpool objpool = New Objectpool ();

Objpool. createpool ();
Object OBJ = objpool. GetObject ();
Returnobject (OBJ );
Objpool. closeobjectpool ();
}
}

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.