Object Pool Pattern

Learn about the object pool design pattern and how to use it.

Description

The object pool design pattern is a creational design pattern in which a pool of objects is initialized and created beforehand and kept in a pool. As and when needed, a client can request an object from the pool, use it, and return it to the pool. The object in the pool is never destroyed.

When to use

We want to use the object pool pattern in the following scenarios:

  • Avoid high runtime creation cost: Use when the cost to create an instance of a class on the fly is high and the number of such instances that will be needed at a particular time is limited.
    Let’s take the example of database (DB) connections. Each of the connection objects’ creation costs is high because there are network calls involved. Also, at a time, not more than a certain number of connections might be needed. The object pool design pattern is perfectly suitable for such cases, ensuring efficient and yet controlled concurrency at scale.

  • Make a collection of resources immutable: Use when the pool object is immutable—take the example of a DB connection again. A DB connection is an immutable object. Almost none of its property needs to be changed.

  • Improve performance: It will boost the application performance significantly when the pool of resources is already created, and we only need to worry about task allocation.

When not to use

Avoid using the object pool pattern in the following scenarios:

  • Simplistic small data structures: When the objects being created are lightweight and inexpensive to instantiate, the overhead of creating new objects is negligible.

  • Unpredictable usage volume: When the read/write usage patterns of objects are unpredictable, maintaining a constant pool of objects does not offer performance gains.

Sample code

Let us create an object pool for ourselves to use whenever we need such a resource pattern.

Get hands-on with 1400+ tech skills courses.