Saturday, January 21, 2012

Android (Java) object pool

There are many ways to implement an object pool. Here's the way it's implemented in some classes in Android (Message, MotionEvent, Parcel, VelocityTracker):

private MyObjectName mNext;
private static Object gPoolSync = new Object();
private static MyObjectName gPool;
private static int gPoolSize = 0;
private static final int MAX_POOL_SIZE = 10;

public static MyObjectName obtain() {
  synchronized (gPoolSync) {
    if (gPool != null) {
      MyObjectName m = gPool;
      gPool = m.mNext;
      m.mNext = null;
      gPoolSize--;
      return m;
    }
  }
  return new MyObjectName();
}

public void recycle() {
  synchronized (gPoolSync) {
    if (gPoolSize < MAX_POOL_SIZE) {
      // Perform object data cleaning and data releasing before recycling
      clearForRecycle();
                
      mNext = gPool;
      gPool = this;
      gPoolSize++;
    }
  }
}

1 comment:

Vadym Stetsiak said...

Very neat approach, indeed. Before I saw this example - I would implement object pool using some sort of queue or stack classes, while now I see that linked list is even better :)