8

My understanding of this is that object pools are useful when we want to work with an object but we want to use one that's already been instantiated. It's like a library book - you check out a book and you return it when you're finished reading it.

However, I struggle to see how this design pattern is used in real life. As a programmer, I have never seen a situation wherein I'd need to check out an object as opposed to creating a new one, passing it in as an argument, or defining a singleton variable containing the object.

2
  • Ah! A singleton is an object pool.
    – moonman239
    Jun 3, 2018 at 0:29
  • It's a pooled object without a pool. ;-) Or, rather the pool is the global environment. Note also that typically Object Pools are Singletons. Jun 3, 2018 at 9:06

3 Answers 3

14

It's useful if the object is re-usable and significantly more expensive to create or destroy than reuse.

Database Connections are a classic case. Connection Pools are common.

  • Microsoft's ODBC implementation offers connection pools.

  • Popular JDBC tools offer connection pooling. Most servlet containers have it.

  • .Net Framework offers connection pooling.

Thread Pools, another popular case.

  • Anything that uses Java Executors. Implementations of Executor are typically Thread Pools, or at least use a thread pool.
  • Many servlet containers, web servers and app servers use thread pools.
  • For example Tomcat, Glassfish, Jetty, Apache, Nginx all use thread pools (per documentation or review of source code).
  • Some databases keep pools of worker threads for similar reasons. For example MySQL, MS SQLServer.

You may never find a case where you need to pool your own objects, but it is likely you will use tools that pool objects.

2
  • 2
    More expensive to create or destroy than to re-use. Jun 3, 2018 at 9:07
  • @JörgWMittag Agreed.
    – joshp
    Jun 3, 2018 at 15:40
4

I use an object pool for acquiring images from a camera in C#. This prevents the Large Object Heap from thrashing and possibly becoming fragmented. By reusing a pool of large byte arrays, I gained a performance optimization and avoid a potential out of resources issue.

1

In game development, it comes up quite often. Even fairly simple objects that are visible (such as projectiles, boxes, etc) often have a non-trivial amount of instantiation involved, and characters even more so.

In the not-uncommon situation that you have a huge number of a given object/creature being created over the course of a level, but only a limited amount present at one time (such as waves of enemies in a vertical shooter), then pooling them is generally much better for performance.

Not the answer you're looking for? Browse other questions tagged or ask your own question.