A simple ObjectPool class.

JAVA TO GO!
Use Object Pools to Sidestep Garbage

Jonathan Amsterdam
Listing 1. A simple ObjectPool class.


/** This class keeps a pool of free objects, to avoid garbage
collection.
*/

 public class ObjectPool {
  protected Object[] freeObjects;
  protected int count;

  public ObjectPool(int nToKeep) {
    freeObjects = new Object[nToKeep];
    count = 0;
  }

  /** Return an object from the free pool if one is available. */

  public Object allocate() {
        return (count == 0? null: freeObjects[--count]);

  }

  /** Put an object into the free pool if there is space for it.
      If there isn't space, let it be garbage collected.
      This doesn't run the finalize() method, because it can't—
      that method is protected. */

  public void free(Object obj) {
    if (count < freeObjects.length)
      freeObjects[count++] = obj;
  }

}