DEV Community

Cover image for Object Pool Pattern
Eyuel Berga Woldemichael
Eyuel Berga Woldemichael

Posted on • Edited on

Object Pool Pattern

Object Pool (resource pools) provide container to reuse objects that are expensive to create.

Motivation

Consider a scenario in which instantiating a new object is resource extensive. The Object Pool pattern solves this problem by providing a mechanism for creating object only when there no cached instance.

Applicability

The Object Pool pattern can be used in cases where:

  • Application contains objects which are expensive to create, resource and performance wise.
  • Clients require same resource but at different time period.
  • When created objects are reusable.
  • When we are working on a job that allocates and re-allocates many objects.

Structure

Object Pool Pattern class diagram

Participants

  • Client: the client uses pooled object type (reusable objects).
  • Reusable Pool: they manage reusable objects for the client.
  • Object Pool: they manage and maintain available objects and collect objects that are requested.

Collaborations

  • Clients configure object pool objects

Advantages

  • It increases performance.
  • Since it uses pools it is easier to manage and reuse, share objects.
  • It reduces time since objects are in pools one can reuse them which decreases significant amount of time.

Disadvantages

  • When reusing objects from the pool unless previous state is changed(reset) it has different output than expected.
  • Once an object is used unless it is sent back (released) to the pool it can’t be used (dependent on the client).

Implementation

The object pool creates objects to be used again (reusable) so when an object is needed it is fetched from the pool or if an object is already waiting it is then returned. Pools are where reusable objects are stored once the object is released it is sent back to the pool.

The implementation of an object pool must also consider a multi-threaded environment. If different threads access the pool concurrently a consistency error will occur. For this reason access to the object pool must be synchronized.

Demo

Let’s suppose in the cafe explained in the introduction of the series, the menus are printed out for every new customer, and are thrown out when the customer leaves. The owners have now realized this is very cost inefficient. They now want to reuse the menus and only print new ones when necessary.

To solve this problem, we first create a generic object pool
class with an abstract create method. Then we use this class to make a concrete EnglishMenuPool. Now we can use checkout and check-in methods to reuse menu object and create new ones when all objects are in use.

Top comments (0)