Skip to content

Object Pool

Roberto Fronteddu edited this page Feb 2, 2023 · 3 revisions

The Object Pool is a Creational Design Pattern. We either pre-create objects of the class or collect unused instances in a memory cache. When code needs an object of this class we provide it from this cache.

Usefull when

  • We need to create instances of a class that is expensive to create and we need a large number of objects of this class for short durations.

Implementation steps

  1. Create the class for the object pool
    • creation must be thread-safe
    • provide methods to get, reset, and release
  2. Decide whether to create new pooled objects when the pool is empty or wait until one of the other instances becomes available.

Example

object-pool-uml

  • AbstractReusable: Abstract product-defining operations
  • ConcreteReusable: Implementation of the reusable product with his own state
  • ObjectPool: Provides a method that the client can use to acquire and release an object of the pool

Considerations

  • Depending on the implementation, we have to decide whether to create new objects when the pool is empty or wait until an object becomes available. This choice depends on whether the object is tied to a fixed number of resources or not.
  • Resetting objects should not be expensive or we risk losing the advantage of caching
  • Pre-caching objects can be helpful and it is a tradeoff between run and start time and memory consumption
  • Reset time should be out of synchronized code or get can be blocked by the reset operation
  • Do not pool long-lived objects, this may reduce performance
  • We do not generally use an object pool to reduce memory allocation or GC, use an object pool when interacting with limited external resources like threads or connections.

Pitfalls

  • Controlling the pool is vital for performance
  • Pooled objects need fast reset functions
  • Hard to use in legacy code as both the client and the reusable object need to be aware that there is an object pool

Comparison with prototype:

Object pool

  • has cached objects that frequently live throughout the program's entire run.
  • Code must explicitly return objects to the pool.

Prototype

  • creates an object when it is needed and no caching is done.
  • Once an object is cloned, no special treatment is necessary.

Real-Life Example:

  • java.util.concurrent.ThreadPoolExecutor
Clone this wiki locally