Object Pooling

Posted by - raja 2008/02/10 07:59:00

Pools of resources for re-use as a performance enhancer

Object Pooling

It is good to share certain things. Definitely, this is true for certain resources and objects.

Object Pooling is about objects being pre-created and "pooled" for later use. The principle tenet behind object pooling is that it is far cheaper to access an object from a pool of identical objects rather than create a new instance of the object. Creating a new instance involves the following steps:

  • Loading the class if not already loaded.
  • Obtaining the required memory from the heap.
  • Creating an instance of the class within the obtained memory.

In the case of object pooling all these steps would have been performed for a pre-configured number of objects already. It was argued that one of these pre-configured objects could be utilized when a new instance is required. After use, this object would be returned to the pool. The problems with this paradigm is that pooling is not cheap. It requires the following steps as part of its execution:

  • The pool should be locked when the object is being obtained.
  • The pool needs to be potentially scanned for unused objects.
  • The object needs to be marked as used in the pool so that it is not available during that duration.
  • The pool can then be unlocked.

All these steps are not cheap since they involved synchronization locks across multiple threads. * Pooling does not automatically support garbage collection. The object needs to be explicitly returned back to the pool to avoid memory leaks. Isn't garbage collection one of the most compelling reasons to use Java or a similar language in the first place? * Objects need to be coded to be "stateless". Otherwise, the object may have to be re-initialized to ensure that it can be re-used back from the pool. This may be a feature of the pooling implementation but would add overhead during deallocation.

In fact according to Cliff Click's Java One 2005 presentation, pooling is worse than object allocation by a factor of 6 or more for small objects and a slight win for heavy objects. Pooling is a good technique for control of objects that govern resources (such as database connections). The reason for this is that it is far more expensive to create those objects due to the networking implications involved. It is not a recommended technique for normal command objects. Hence we can state that resource pooling makes sense not object pooling.