Skip to content

Design Patterns

Object Pool

Getting or returning one object takes O(1) time (a constant amount). The savings come from skipping repeated, costly creation.

The idea, in plain English

An object pool works like a library lending out books. The library doesn't print a brand-new book for every visitor. It keeps a fixed set of copies, lends one out when you ask, and takes it back onto the shelf when you're done. Then the next person can borrow that same copy. In code, a pool keeps a set of costly-to-create objects ready to reuse, instead of constantly building and throwing them away.

How it works

  1. 1You create a fixed batch of objects up front and keep them in an 'available' list.
  2. 2When someone needs one, you hand out an object from that list and move it to an 'in use' list.
  3. 3When they're done, you put it back in the 'available' list. The next request reuses that very same object, instead of building a new one.

When you'd use it

Use this when creating an object is costly — database connections, network sockets, or big buffers — and you'd rather reuse a small set of them than keep creating and destroying new ones.

Common beginner mistakes

  • Always release an object back to the pool, or the pool slowly runs out, even though nothing still uses them.
  • Reset an object before lending it out again, so it doesn't still hold old data from its last use.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Using connection #1
Using connection #2
Third request while both are out: none available
After releasing one: Using connection #1
Same connection object reused? yes

Not sure this is the right topic? See the learning paths → or where this leads →