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;
  }

}

Upcoming Training Events

0 AM
Visual Studio Live! San Diego
September 8-12, 2025
Live! 360 Orlando
November 16-21, 2025
Cloud & Containers Live! Orlando
November 16-21, 2025
Data Platform Live! Orlando
November 16-21, 2025
Visual Studio Live! Orlando
November 16-21, 2025