Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 57 ยท Creational Patterns

Object Pool, Lazy Initialization and Dependency-Free Creation

Learn the Object Pool and Lazy Initialization patterns: reuse expensive objects, write a connection pool, build a lazy proxy and know when not to pool.

The classic GoF creational patterns decide which object to create and how. Two more patterns, not in the original book but very common in real systems, decide when to create it and whether to create it at all. An Object Pool keeps a set of expensive objects alive and lends them out instead of creating and destroying them repeatedly. Lazy Initialization delays creating an object until the first moment someone really needs it.

Both save resources, and both add state and failure modes. This lesson shows each one running, ends with a list of situations where pooling is a mistake, and explains the idea behind "dependency-free creation": creating a heavy collaborator only when needed, so that building the surrounding object stays cheap and needs nothing to be ready up front.

Two ways to spend less

Object pool Reuse objects that are costly to create.
Lazy init Create only on first real use.
Lazy proxy A stand-in that builds the real one later.
1 / 2

Object Pool

Some objects are slow or heavy to create: a database connection (network handshake, authentication), a thread, a large buffer, a compiled regular expression engine. If every request creates and discards one, the program wastes most of its time on setup. A pool creates a few up front or on demand, then hands them out and takes them back.

A pool has four responsibilities:

  • Create objects on demand up to a maximum, so resources stay bounded.
  • Lend an idle object when one exists.
  • Queue callers when every object is in use and the maximum is reached.
  • Reset returned objects so the next borrower never sees the previous borrower's state.

Real connection pools (HikariCP in Java, pg.Pool in Node, SQLAlchemy's pool in Python) do all of that and add health checks and timeouts. The Node.js program below is a stand-in that models the same behavior with fake connections, so it runs anywhere and prints a predictable result.

Node.js A connection pool with a waiting queue (Node.js)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Six jobs ran over two connections. Jobs 3 to 6 waited in the queue and received a connection the moment an earlier job released one. The try/finally inside use() is the most important line in the design: if the borrower forgets to release, the pool slowly runs dry, a pool leak. Wrapping acquire/release in a function that guarantees the release (Java's try-with-resources, Python's with, C++ RAII guards) removes that whole category of bug.

Lazy initialization

Lazy initialization postpones creation until first use. Startup gets faster, and an object that is never needed never costs anything. The simplest form is a getter that creates the value once and caches it.

Java
// Read-only Java: thread-safe lazy holder idiom
class Reports {
    private static class Holder {
        static final PdfEngine INSTANCE = new PdfEngine(); // created on first access
    }
    static PdfEngine engine() { return Holder.INSTANCE; }
}

In JavaScript a small lazy() helper does the job, and you can inject the factory so tests stay in control:

JS A memoized lazy value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The index was built exactly once, on first use, and not at startup. Marking created only after the factory succeeds lets a failed build be retried. The price of laziness is that the first caller pays the cost, which can be a slow first request, and that errors appear late, in the middle of some unrelated operation. Teams often choose to initialize eagerly at startup precisely so that failures show up at deploy time.

In multi-threaded Java and C++ the check-then-create sequence is a race. Use the holder idiom above, std::call_once or a static local variable in C++, or a language-level lazy type (Lazy<T> in C#, functools.cached_property in Python).

The lazy proxy

A lazy proxy (also called a virtual proxy) looks exactly like the real object but creates it on the first call. Callers hold the proxy from the start, so the code that needs the object does not change; only the creation moves. This is where "dependency-free creation" pays off: a service can be built with all its heavy collaborators as cheap proxies, so construction needs nothing to be running yet. The real database, mail client or model loads when something finally calls it. You will meet the general proxy pattern in a later lesson; here is the lazy variant using JavaScript's built-in Proxy:

Node.js A lazy proxy that builds the real object on first call (Node.js)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The "loading fonts" line prints exactly once, and only when the first paid order arrives. CheckoutService is unaware that it holds a proxy; it just calls render. That separation is why a lazy proxy is easy to retrofit.

Lazy loading variants: virtual proxy, value holder and ghost

When the thing you load lazily is data from a database or file, three variants of lazy loading are common in persistence code (they are the ones Martin Fowler catalogs under "Lazy Load"). The lazy proxy above is the first. The others trade transparency for simplicity or for efficiency.

  • Virtual proxy: an object with the same interface as the real one. The first call loads the real data. Callers cannot tell the difference, but it needs a proxy class (or runtime-generated proxy) for each type.
  • Value holder: a small generic wrapper with an explicit getValue(). The caller knows the value is lazy and asks for it. Easy to write for any type, but the laziness is visible in your API.
  • Ghost: a real object of the real class, created with only its identity (an id) and marked "not loaded". The first time any property is read, it loads all its fields and marks itself loaded. There is no wrapper at all; the object is its own lazy loader.
JS Three ways to defer loading an author

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each variant ran exactly one query, and only when data was first needed. Reading the id never triggers a load, because the ghost and the proxy already know it. That is why a list of 500 books can hold 500 author references without 500 queries: only the authors you display are loaded.

Virtual proxy Value holder Ghost
Caller sees The normal type A holder: getValue() The normal type
Extra classes A proxy per type One generic holder None, but logic inside each class
Loads On first method call On getValue() All fields on first property read
Identity Proxy differs from the real object Holder differs from the value The object is the same one throughout
Typical use Hand-written or generated wrappers Simple code and languages with lambdas ORMs that need to avoid wrapper identity problems

ORMs such as Hibernate and Doctrine use proxies (or generated subclasses that behave like ghosts) for lazy associations. Two traps appear in all three: the N+1 query problem, where looping over a list triggers one query per item (fix it by loading the related rows together, for example with a join or "eager fetch" for that query), and lazy loading outside its session, where a detached object tries to load after the connection is closed and fails. Choose lazy loading for rarely-read, expensive relations, and load eagerly what you almost always need.

When pooling is a mistake

Pools are a performance tool, and like all performance tools they should follow a measurement. Avoid or remove a pool when:

  • Objects are cheap. Modern allocators and garbage collectors make small short-lived objects nearly free. Pooling a Point or a String usually makes the program slower and more complex. Pools pay off for objects with expensive creation: connections, threads, large buffers, native handles.
  • State can leak between users. An object returned with leftover data is a bug, and sometimes a security hole. If reset() cannot be made reliable, create fresh ones.
  • The pool becomes the bottleneck. A tiny maximum with long-running borrowers makes everything queue. Size pools from measured load, not guesses.
  • Objects age badly. Connections drop; pooled ones may be dead when borrowed. Production pools validate objects before lending them.
  • Lifetime is already managed. Thread pools, HTTP clients and database drivers usually come with one. Do not write a second pool on top.

Lazy initialization has its own mistakes: hiding startup failures until traffic arrives, racing in threaded code, and creating hidden global state, the same problems as an unmanaged Singleton. When you want one lazily created shared instance, prefer injecting it, as discussed in Dependency Inversion.

That closes the creational chapter: Factory Method and Abstract Factory choose classes, Builder assembles, Prototype copies, and pools and lazy creation control timing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main reason to use an Object Pool?

    Pools amortize the cost of creating heavy objects such as connections or threads by lending them out repeatedly.
  2. 2. Why does the pool's use() method release the connection inside finally?

    Without a guaranteed release, an exception would keep the object borrowed forever and the pool would eventually run dry.
  3. 3. What happens when all pooled objects are in use and the maximum size is reached?

    A bounded pool queues callers, which keeps resource use under the limit.
  4. 4. Which is a drawback of lazy initialization?

    Creation moves to the first use, which can make that request slow and delay the discovery of configuration errors.
  5. 5. In which case is pooling most likely a mistake?

    Small objects are cheap to allocate and collect, so a pool adds complexity and often slows the program down.

Summary

  • An Object Pool lends out a bounded set of expensive objects, queues callers at the limit, resets objects on return and must always release them (try/finally, with, RAII).
  • Lazy initialization creates a value on first use and caches it; set the cached flag only after creation succeeds.
  • A lazy proxy has the same interface as the real object and builds it on the first call, so heavy collaborators need not exist when the owner is constructed.
  • Pools help for costly objects such as connections and threads, and hurt for cheap ones or when state can leak.
  • Laziness trades a faster start for a slow first use, late errors and races in threaded code.

Next lesson: Adapter.