A class that uses an object pool.

JAVA TO GO!
Use Object Pools to Sidestep Garbage

Jonathan Amsterdam
Listing 2. A class that uses an object pool.


public class PooledPoint {
    private static ObjectPool pool = new ObjectPool(100);
    private int x, y;

    public static PooledPoint create(int x, int y) {
        PooledPoint p = (PooledPoint) pool.allocate();
        if (p == null)
            p = new PooledPoint();
        p.init(x, y);
        return p;
    }

    private PooledPoint() {}

    private void init(int x, int y) {
      this.x = x;
      this.y = y;
    }
    
    public void free() {
      this.finalize();
      pool.free(this);
    }    
}