ObjectPool Design Pattern

object pool design pattern image

Definition
ObjectPool pattern is used for sharing and reusing the resources  that are expensive to create.



  • Reusable wraps the limited resource, will be shared by several clients for a limited amount of time.
  • ReusablePool manages the reusable objects for use by Clients, creating and managing a pool of objects.
  • Client  uses an instance of type Reusable.

When a client asks for a Reusable object, the pool performs the following actions:
  • Search for an available Reusable object and if it was found it will be returned to the client.
  • If no Reusable object was found then it tries to create a new one. If this actions succeeds the new Reusable object will be returned to the client.
  • If the pool was unable to create a new Reusable, the pool will wait until a reusable object will be released
However, we don’t want a process to have to wait for a particular object to be released, so the Object Pool also instantiates new objects as they are required, but must also implement a facility to clean up unused objects periodically.

Applicability
  • ObjectPool is used whenever there are several clients who needs the same stateless resource which is expensive to create.
  • ObjectPool is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

Consequences
  • Object pooling can offer a significant performance boost

Downsides
  • The objects should be released by the client when it finishes using them. There are plenty of examples when the client ”forget” to release the resources.
  • In order to work in a multithreading environment the methods that are used by differnt threads should be synchronized. 

Sample Code


Related Patterns
  • Although  ObjectPool and Flyweight patterns have similarity, but they have the following differences:
    • Although the object pool is handling the object instantiation it's main purpose is to provide a way for the clients to reuse the objects like they are new objects, without being shared and reused during they are acquired, but in Flyweight objects are shared.
    • Flyweight objects are usually immutable, whereas ObjectPool's Reusable objects are usually mutable. 
    • An object pool is usually a container for a set of domain objects while a flyweight usually is a domain object.
  • The Factory Method pattern can be used to encapsulate the creation logic for objects. However, it does not manage them after their creation, the object pool pattern keeps track of the objects it creates. 
  • Object Pools are usually implemented as Singletons.

Comments

Popular Posts