ObjectPool

原创 2006年06月10日 12:03:00

/*
*Free object pools represent a form of object reuse.
*With the free pool approach, code using objects of the pooled type must track usage and
*explicitly return the objects to the free pool when usage is completed.
*
*When an object is needed, the free pool removes one from tha available collection and
*reinitializes it, rather than constructing a new object.
*The free pool only constructs a new object of the pooled type when the available collection is empty.
*/

/*
*Unfortunately, it's slower than just allocatiing the Rectangle object directly!!
*All the generic code (esp the extensive use of type casts) along with the synchronization of the LinkedList class,
*adds so much overhead to bookkeeping.
*So, a common problem with generic code -- it provides code reuse, but generally with a performance penalty.
*/

//This is a generic code of the ObjectPool

import java.util.*;
import java.awt.*;

public class ObjectPool{
      private final Class objectType;
      private final LinkedList freeStack;

      //Designate a specific type of the objects pulled into the object pool.
      public ObjectPool(Class type){
            objectType = type;
            freeStack = new LinkedList();
      }

      public int getPoolSize(){
            return freeStack.size();
      }

      public synchronized Object getInstance(){
            //Check if the pool is empty, create a new object if so
            //try……catch…… blocks are needed when it creates new object.
            if (freeStack.isEmpty()){
                  try{
                        System.out.println("Create a new object.");
                        return objectType.newInstance();
                  }
                  catch (InstantiationException e) {}
                  catch (IllegalAccessException e) {}
                  //Throw unchecked exception for error in pool configuration.
                  throw new RuntimeException ("Failed to create a new object for pool.");
            }
            else{
                  //Remove object from the end of free pool
                  Object result = freeStack.removeLast();
                  System.out.println("Get instance from the free pool.");
                  return result;
            }
     }

     //return the objects to the free pool when usage is completed
     public synchronized void freeInstance(Object obj){
           if (objectType.isInstance(obj)) freeStack.add(obj);
           else throw new IllegalArgumentException("Argument type invalid for pool");
     }

}

class ObjectPoolTest{
      private static final ObjectPool rectanglePool = new ObjectPool(Rectangle.class);

      private static Rectangle getRectangleObject(int height, int width, int x, int y){
            Rectangle rect = (Rectangle)rectanglePool.getInstance();
            rect.height = height;
            rect.width = width;
            rect.x = x;
            rect.y = y;
            return rect;
      }
   
      class AnotherThread extends Thread{
            private int loopTimes = 10;

            AnotherThread(){
                  super("Another Thread");
            }

            public void run(){
                  for (int i = 0; i < loopTimes; i++){
                        //Construct a rectangle to b passed.
                        Rectangle rect = getRectangleObject(i, i, i, i);
                        //Do something with the object
                        //…………………………
                        //Return passed rectangle to pool.
                        rectanglePool.freeInstance(rect);    
                  }
            }
      }

      AnotherThread t = new AnotherThread();

      public static void main(String[] args){
            ObjectPoolTest opt = new ObjectPoolTest();
            int loopTimes =10;
  
            opt.t.start();
            for (int i = 0; i < loopTimes; i++){
                  //Construct a rectangle to b passed.
                  Rectangle rect = getRectangleObject(i, i, i, i);
                  //Do something with the object
                  //…………………………
                  //Return passed rectangle to pool.
                  rectanglePool.freeInstance(rect);    
            }
            try{
                  opt.t.join();   
            }catch (InterruptedException e){}
            System.out.println("The number of objects in the pool at last is " + rectanglePool.getPoolSize());
      }

}

相关文章推荐

ObjectPool_v1.0

  • 2008年08月01日 15:16
  • 63KB
  • 下载

PoolableObjectFactory和ObjectPool

commons-pool包里主要包括三个重要的接口: ObjectPool用于管理要被池化的对象的借出和归还; ObjectPoolFactory用于大量生成相同类型和设置的ObjectPool...

使用对象池(ObjectPool)方式处理子弹的发射逻辑

对应对象池个概念,网上有很多,而且关于在unity里面使用对象池的文章也很多,我这里就直接上代码好了: using UnityEngine; using System.Collect...

Unity优化之ObjectPool-关于初始化

在Unity制作游戏的使用过程中为避免卡顿经常会使用ObjectPool.但要记得PaticleSystem和TrailRender的初始化....
  • ainn_pp
  • ainn_pp
  • 2014年08月22日 14:34
  • 1067

ObjectPool

ObjectPool ObjectPool 定义了一个简单的池接口 BaseObjectPool以下三个类的父类     A simple base implementa...

Unity3D对象池技术(ObjectPool)小例子

ObjectPool 对象池脚本这里面用继承单例框架脚本,此脚本在我的另一篇博客上单例框架脚本using UnityEngine; using System.Collections; using Sy...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:ObjectPool
举报原因:
原因补充:

(最多只允许输入30个字)