An example of Object pool mode programming in Java design pattern _java

Source: Internet
Author: User
Tags static class

Defined
An Object pool is a collection of objects that have been initialized and can be used, and users of the pool can take objects from the pool, manipulate them, and return to the pool instead of destroying it when they are not needed.

If the cost of initialization and instantiation is high and needs to be instantiated frequently, the use of object pooling can achieve significant performance gains with fewer instances per instantiation. The time taken to get objects from the pool is predictable, but the time required to create a new instance is indeterminate.

Realize

1. Reusable-objects in the object pool are usually expensive to instantiate.
2. Client-Uses an instance of an object.
3. Reusablepool-Manage the instantiation, recovery and destruction of objects.

The main idea in a single instance
1. A stack, here with stack
2. Initialization method, the container can be opened in advance to create a pool
3. How to create an instance
4. Provides methods for obtaining object instances from the pool
5. Provision of the return method, the consequences of not return very serious
6. Control the request wait time method, after a certain event has not obtained an object instance, return a null pointer

Import Java.util.Stack; @SuppressWarnings ("Unchecked") public class Objectpool {public Objectpool () {} private Poolparam Poolparam 
 
  ; 
  public void Setpoolparam (Poolparam poolparam) {this.poolparam = Poolparam; 
 
  }//Current total object number private int currentnum = 0; 
 
  Private Class Clazz; 
  public void Setclazz (Class clazz) {this.clazz = Clazz; 
 
  }//stack, used to store objects, simulate a pool private stack stack; 
  Public stack Getstack () {return stack; 
  public void Setstack (stack stack) {this.stack = stack; 
 
  }//... ............. ....... ......... ... the count variable private int timewait = 0 for which the timeout is waiting for the number of times to be timed out. \ n ................ ........ ... ................. ........//Create object pool public void Initalpool (Poolpara 
    M Poolparam, Class clazz) {this.setpoolparam (Poolparam); 
 
    This.setclazz (Clazz); 
 
    stack = new stack (); 
 
    Stack.clear (); System.out.println ("obj.. Pool is initial ... ");
    Build the minimum number of objects to configure and push to the stack try {for (int i = 0; i < Poolparam.getminobjectcount (); i++) {//according to P 
      Oolparam Initialization Object Pool Stack.push (Clazz.newinstance ()); 
    } catch (Instantiationexception e) {e.printstacktrace (); 
    catch (Illegalaccessexception e) {e.printstacktrace (); 
    }///Create individual Object Private Object Createobj (Class clazz) {object obj = null; 
 
      try {obj = clazz.newinstance (); 
    System.out.println ("A new one ..."); 
    catch (Instantiationexception e) {e.printstacktrace (); 
    catch (Illegalaccessexception e) {e.printstacktrace (); 
  return obj; 
 
    ///Object pool provided Get method public Object getinstance () {//System.out.println (Stack.size ()); 
 
    object = null; if (stack.size () = = 0) {//If the current stack has a length of 0 and the total number of objects does not exceed the defined maximum number of if (Currentnum + poolparam.getminobjectcount ()) & Lt 
 
Poolparam. Getmaxobjectcount ()) {        Creates a new object = This.createobj (Clazz); 
 
      Number of objects +1 currentnum++; 
          else {synchronized (this) {try {waitme (this); 
          catch (Exception e) {e.printstacktrace (); 
          ////After notification the detection stack is empty and gives the resource just released if (!stack.empty ()) {object = Stack.pop (); 
 
      else if (stack.size () > 0) {object = Stack.pop (); 
    System.out.println (Stack.size ()); 
  return object; 
 
      }//Returns the object's method public void Returnobj (object obj) {if (clazz.isinstance (obj)) {stack.push (obj); 
      Synchronized (This) {notify (); 
    } else {System.out.println ("This object can not push to stack!"); 
      Wait recursive algorithm private void Waitme (Objectpool pool) {//wait 2s technical control if (timewait >= 2000) { System.out.println ("Jump up the" step ...)); 
      timewait = 0; 
 
    Return 
 
        else {try {pool.wait (500); 
        Wait for the count to accumulate. 
 
        Timewait +=1000; 
 
        System.out.println ("Waiting time to free obj."); 
          if (Stack.empty ()) {System.out.println ("agian ..."); 
        Waitme (pool); 
      } catch (Interruptedexception e) {e.printstacktrace (); 
 } 
    } 
  } 
 
}

&NBSP
To manage the pool class, this is not difficult, synchronization is good

@SuppressWarnings ("Unchecked") public class Objectpoolmanage {private Objectpoolmanage () {} private Stati 
   
 
 
  c Objectpool Pool; To achieve a single example of the acquisition method .... 
    The default public static synchronized Objectpool Getcacheobject (Class clazz) {if (null!= pool) {return pool; 
      else {Createobjectpool (null, clazz); 
    return pool; }//Implementation of a single instance of the Acquisition method ... 
      Custom public static synchronized Objectpool getcacheobject (Poolparam p, Class clazz) {if (null!= pool) { 
    return pool; 
      else {Createobjectpool (P, clazz); 
    return pool; 
 
    } private static Objectpool Createobjectpool (Poolparam p, Class clazz) {pool = new objectpool (); 
    if (null = = P) {Pool.initalpool (new Poolparam (5,10), clazz); 
    else {Pool.initalpool (P, clazz); 
  } return pool; 
     
    private static Class Getclazz () {class clazz=null; try {clazz= Class.forName (pPp.getpropertybyname ("ObjectPath")); 
    catch (ClassNotFoundException e) {e.printstacktrace (); 
  return clazz; 
 } 
}


related issues and implementations
1. Object pools can limit the number of objects, and when the limit is exceeded, the object pool needs to return an exception or null value to notify the customer.
2. In a multithreaded environment, the checkout and checkin methods require synchronization.
3. Timed cleanup of expired objects.

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.