Programming Search⌘K

Patterncore

Object pool

Also called Object Pool, object pool pattern, resource pool, free list, pooling.

A pool keeps a set of ready objects. A client acquires one, uses it and releases it, and the pool resets it for the next client, so a costly object is not created again.

Family
creational-design
Intent
Keep a set of initialized objects ready for use, so that a client acquires an object from the set and returns it after use, in place of creating and destroying a costly object each time.
Also called
Resource Pool

Intent

Keep a set of initialized objects ready for use. A client acquires an object from the set, uses it, and returns it. The object is not destroyed, and the next client gets it in place of a new one.1

Problem

A server opens a connection to a database for each request. To open a connection, the program must set up a socket, do a handshake, parse the connection string and authenticate. Each step takes time.2 A server that handles many short requests spends more time to open and close connections than to use them.

The same problem comes with other objects that are costly to create: threads, large buffers, and objects that hold a native resource. The forces are these:

  • Creation is costly, and the program needs the object often but for a short time.
  • The program uses only a few objects at the same time, so a small set can serve all requests.
  • After use, the object can be put back into a known state, so that the next user can use it as if it were new.

Solution

Put a pool between the clients and the creation of the objects. The pool keeps a set of idle objects. Acquire takes an idle object, or creates one when the set is empty. Release resets the object and puts it back.1

 Client                    Pool                          Reusable
 ------                    ---------------------------   --------
 b = pool.acquire() -----> idle empty? create() ------->  new Buffer
                           else pop an idle object
 use b
 pool.release(b)  -------> reset(b)
                           idle below max_idle? keep b
                           else drop b

The participants are the pool, the reusable object and the client. The pool also holds two policies:

  • Sizing. A pool can limit the objects it keeps idle, the objects it creates in total, or both. The ASP.NET Core ObjectPool limits only the objects that it retains, not the objects that it allocates.3
  • Empty pool. When no object is idle, a pool can fail and return an error, create a new object, or, in a program with threads, block the client until another thread returns an object.1

Each pool must make release reliable. In a language with destructors, a smart pointer can return the object when it goes out of scope. In a language with garbage collection, the client must release the object in a finally block, a with block, or a using statement. A finalizer is a poor choice, because there is usually no guarantee when it runs, or whether it runs at all.1

Example

The example files show one pool in each language. The pool keeps at most two idle buffers. Three requests run one after another and share one buffer. Then three requests run at the same time, so the pool creates two more buffers. After the release, the pool keeps two buffers and drops the third. Each example releases the buffer with the scoped form of its language:

Language Release Thread safety
Python a contextmanager and a with block threading.Lock
JavaScript a callback in try and finally one thread, so no lock
TypeScript a generic Pool<T> with a callback one thread, so no lock
Java try and finally synchronized methods
C# a lease that implements IDisposable, in a using statement lock
C++ std::unique_ptr with a custom deleter (RAII) std::mutex
Go defer; idle items in a buffered channel4 the channel
Rust a guard type that implements Drop Mutex
PythonGitHub
import threading
from contextlib import contextmanager


class Buffer:
    def __init__(self, ident: int):
        self.ident = ident  # a real buffer would be costly to create
        self.parts: list[str] = []

    def write(self, text: str) -> None:
        self.parts.append(text)

    def text(self) -> str:
        return " ".join(self.parts)


class Pool:
    def __init__(self, create, reset, max_idle: int):
        self._create, self._reset, self._max_idle = create, reset, max_idle
        self._idle: list = []
        self._lock = threading.Lock()
        self.created = 0

    def acquire(self):
        with self._lock:
            if self._idle:
                return self._idle.pop()
            self.created += 1
            return self._create(self.created)

    def release(self, item) -> None:
        self._reset(item)  # clear the state before the next user sees it
        with self._lock:
            if len(self._idle) < self._max_idle:
                self._idle.append(item)  # else: drop it, the pool is full

    @contextmanager
    def lease(self):
        item = self.acquire()
        try:
            yield item
        finally:
            self.release(item)  # runs even if the body raises

    def idle(self) -> int:
        return len(self._idle)


pool = Pool(create=Buffer, reset=lambda b: b.parts.clear(), max_idle=2)
for i in range(1, 4):
    with pool.lease() as b:
        b.write(f"request {i}")
        print(f"request {i} -> buffer #{b.ident}: {b.text()}")

held = [pool.acquire() for _ in range(3)]
print("3 at once -> buffers", " ".join(f"#{b.ident}" for b in sorted(held, key=lambda b: b.ident)))
for b in held:
    pool.release(b)
print("idle after release:", pool.idle())
print("created:", pool.created)
Output
request 1 -> buffer #1: request 1
request 2 -> buffer #1: request 2
request 3 -> buffer #1: request 3
3 at once -> buffers #1 #2 #3
idle after release: 2
created: 3
  • Verdict: idiom. The standard library has no general object pool. A list and a lock are enough, and a contextmanager makes the release automatic in a with block.
  • For a pool of threads or processes, use concurrent.futures.ThreadPoolExecutor or multiprocessing.Pool. Database drivers and libraries such as SQLAlchemy have their own connection pools.
  • CPython frees most objects as soon as the last reference goes, so a pool of plain Python objects rarely saves time. Pool the costly resource, not the wrapper.
#include <algorithm>
#include <functional>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <vector>

struct Buffer {
    explicit Buffer(int id) : id(id) {}  // a real buffer would be costly to create
    int id;
    std::string text;
};

template <typename T>
class Pool {
public:
    using Deleter = std::function<void(T*)>;
    using Handle = std::unique_ptr<T, Deleter>;

    Pool(std::function<std::unique_ptr<T>(int)> create, std::function<void(T&)> reset, std::size_t max_idle)
        : create_(std::move(create)), reset_(std::move(reset)), max_idle_(max_idle) {}

    // The handle returns the item to the pool when it goes out of scope.
    Handle acquire() {
        std::unique_ptr<T> item;
        {
            std::lock_guard<std::mutex> lock(mu_);
            if (!idle_.empty()) {
                item = std::move(idle_.back());
                idle_.pop_back();
            } else {
                item = create_(++created_);
            }
        }
        return Handle(item.release(), [this](T* p) { release(std::unique_ptr<T>(p)); });
    }

    std::size_t idle() {
        std::lock_guard<std::mutex> lock(mu_);
        return idle_.size();
    }
    int created() const { return created_; }

private:
    void release(std::unique_ptr<T> item) {
        reset_(*item);  // clear the state before the next user sees it
        std::lock_guard<std::mutex> lock(mu_);
        if (idle_.size() < max_idle_) idle_.push_back(std::move(item));
        // else: item is destroyed here, the pool is full
    }

    std::function<std::unique_ptr<T>(int)> create_;
    std::function<void(T&)> reset_;
    std::size_t max_idle_;
    std::mutex mu_;
    std::vector<std::unique_ptr<T>> idle_;
    int created_ = 0;
};

int main() {
    Pool<Buffer> pool([](int id) { return std::make_unique<Buffer>(id); },
                      [](Buffer& b) { b.text.clear(); }, 2);
    for (int i = 1; i <= 3; ++i) {
        auto b = pool.acquire();
        b->text = "request " + std::to_string(i);
        std::cout << "request " << i << " -> buffer #" << b->id << ": " << b->text << "\n";
    }  // b goes back to the pool here

    {
        std::vector<Pool<Buffer>::Handle> held;
        for (int i = 0; i < 3; ++i) held.push_back(pool.acquire());
        std::vector<int> ids;
        for (auto& b : held) ids.push_back(b->id);
        std::sort(ids.begin(), ids.end());
        std::cout << "3 at once -> buffers";
        for (int id : ids) std::cout << " #" << id;
        std::cout << "\n";
    }  // all three go back here
    std::cout << "idle after release: " << pool.idle() << "\n";
    std::cout << "created: " << pool.created() << "\n";
}
Output
request 1 -> buffer #1: request 1
request 2 -> buffer #1: request 2
request 3 -> buffer #1: request 3
3 at once -> buffers #1 #2 #3
idle after release: 2
created: 3
  • Verdict: idiom. The standard library has no object pool. A std::unique_ptr with a custom deleter returns the item to the pool when the handle is destroyed, so RAII does the release.
  • The pool must live longer than every handle, because the deleter holds a pointer to it.
  • Pools in C++ often hold memory rather than objects: std::pmr::unsynchronized_pool_resource gives pooled allocation to the std::pmr containers.
JavaGitHub
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.IntFunction;

public class Main {
    static final class Buffer {
        final int id; // a real buffer would be costly to create
        final StringBuilder text = new StringBuilder();

        Buffer(int id) {
            this.id = id;
        }
    }

    static final class Pool<T> {
        private final ArrayDeque<T> idle = new ArrayDeque<>();
        private final IntFunction<T> create;
        private final Consumer<T> reset;
        private final int maxIdle;
        private int created;

        Pool(IntFunction<T> create, Consumer<T> reset, int maxIdle) {
            this.create = create;
            this.reset = reset;
            this.maxIdle = maxIdle;
        }

        synchronized T acquire() {
            T item = idle.pollFirst();
            if (item != null) {
                return item;
            }
            created++;
            return create.apply(created);
        }

        void release(T item) {
            reset.accept(item); // clear the state before the next user sees it
            synchronized (this) {
                if (idle.size() < maxIdle) {
                    idle.addFirst(item);
                }
            }
        }

        synchronized int idle() {
            return idle.size();
        }

        synchronized int created() {
            return created;
        }
    }

    public static void main(String[] args) {
        Pool<Buffer> pool = new Pool<>(Buffer::new, b -> b.text.setLength(0), 2);
        for (int i = 1; i <= 3; i++) {
            Buffer b = pool.acquire();
            try {
                b.text.append("request ").append(i);
                System.out.println("request " + i + " -> buffer #" + b.id + ": " + b.text);
            } finally {
                pool.release(b); // runs even if the body throws
            }
        }

        List<Buffer> held = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            held.add(pool.acquire());
        }
        StringBuilder ids = new StringBuilder();
        held.stream().mapToInt(b -> b.id).sorted().forEach(id -> ids.append(" #").append(id));
        System.out.println("3 at once -> buffers" + ids);
        held.forEach(pool::release);
        System.out.println("idle after release: " + pool.idle());
        System.out.println("created: " + pool.created());
    }
}
Output
request 1 -> buffer #1: request 1
request 2 -> buffer #1: request 2
request 3 -> buffer #1: request 3
3 at once -> buffers #1 #2 #3
idle after release: 2
created: 3
  • Verdict: library. The JDK has thread pools (java.util.concurrent.Executors) but no general object pool. Apache Commons Pool gives one, and JDBC connection pools are the common case.
  • The synchronized methods make the pool safe for many threads. The reset runs outside the lock, because it touches only the item.
  • A modern JVM allocates small objects fast, so pool only objects with a real creation cost: connections, threads, large buffers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

sealed class Buffer
{
    public readonly int Id; // a real buffer would be costly to create
    public readonly StringBuilder Text = new();
    public Buffer(int id) => Id = id;
}

sealed class Pool<T> where T : class
{
    private readonly Stack<T> idle = new();
    private readonly Func<int, T> create;
    private readonly Action<T> reset;
    private readonly int maxIdle;
    private readonly object gate = new();
    public int Created { get; private set; }

    public Pool(Func<int, T> create, Action<T> reset, int maxIdle) =>
        (this.create, this.reset, this.maxIdle) = (create, reset, maxIdle);

    public T Acquire()
    {
        lock (gate)
        {
            if (idle.Count > 0) return idle.Pop();
            Created++;
            return create(Created);
        }
    }

    public void Release(T item)
    {
        reset(item); // clear the state before the next user sees it
        lock (gate)
        {
            if (idle.Count < maxIdle) idle.Push(item);
        }
    }

    public Lease Rent() => new Lease(this, Acquire());

    public int Idle { get { lock (gate) return idle.Count; } }

    public readonly struct Lease : IDisposable
    {
        private readonly Pool<T> pool;
        public T Item { get; }
        public Lease(Pool<T> pool, T item) => (this.pool, Item) = (pool, item);
        public void Dispose() => pool.Release(Item); // called at the end of a using block
    }
}

static class Program
{
    static void Main()
    {
        var pool = new Pool<Buffer>(id => new Buffer(id), b => b.Text.Clear(), 2);
        for (int i = 1; i <= 3; i++)
        {
            using var lease = pool.Rent();
            lease.Item.Text.Append($"request {i}");
            Console.WriteLine($"request {i} -> buffer #{lease.Item.Id}: {lease.Item.Text}");
        }

        var held = new List<Buffer> { pool.Acquire(), pool.Acquire(), pool.Acquire() };
        Console.WriteLine("3 at once -> buffers " + string.Join(" ", held.Select(b => b.Id).Order().Select(id => $"#{id}")));
        foreach (var b in held) pool.Release(b);
        Console.WriteLine($"idle after release: {pool.Idle}");
        Console.WriteLine($"created: {pool.Created}");
    }
}
Output
request 1 -> buffer #1: request 1
request 2 -> buffer #1: request 2
request 3 -> buffer #1: request 3
3 at once -> buffers #1 #2 #3
idle after release: 2
created: 3
  • Verdict: stdlib. .NET has System.Buffers.ArrayPool<T> for arrays, and the package Microsoft.Extensions.ObjectPool for other objects. The example writes its own pool to show the parts.
  • A lease that implements IDisposable lets a using statement return the item at the end of the scope.
  • ADO.NET pools database connections behind SqlConnection.Open and Close, so most code uses a pool without seeing it.
JavaScriptGitHub
class Buffer {
  constructor(id) {
    this.id = id; // a real buffer would be costly to create
    this.parts = [];
  }
  write(text) {
    this.parts.push(text);
  }
  text() {
    return this.parts.join(" ");
  }
}

class Pool {
  #idle = [];
  constructor(create, reset, maxIdle) {
    this.create = create;
    this.reset = reset;
    this.maxIdle = maxIdle;
    this.created = 0;
  }
  acquire() {
    if (this.#idle.length > 0) return this.#idle.pop();
    this.created += 1;
    return this.create(this.created);
  }
  release(item) {
    this.reset(item); // clear the state before the next user sees it
    if (this.#idle.length < this.maxIdle) this.#idle.push(item);
  }
  use(fn) {
    const item = this.acquire();
    try {
      return fn(item);
    } finally {
      this.release(item); // runs even if fn throws
    }
  }
  get idle() {
    return this.#idle.length;
  }
}

const pool = new Pool((id) => new Buffer(id), (b) => { b.parts.length = 0; }, 2);
for (let i = 1; i <= 3; i++) {
  pool.use((b) => {
    b.write(`request ${i}`);
    console.log(`request ${i} -> buffer #${b.id}: ${b.text()}`);
  });
}

const held = [pool.acquire(), pool.acquire(), pool.acquire()];
console.log("3 at once -> buffers", held.map((b) => `#${b.id}`).sort().join(" "));
for (const b of held) pool.release(b);
console.log("idle after release:", pool.idle);
console.log("created:", pool.created);
Output
request 1 -> buffer #1: request 1
request 2 -> buffer #1: request 2
request 3 -> buffer #1: request 3
3 at once -> buffers #1 #2 #3
idle after release: 2
created: 3
  • Verdict: idiom. JavaScript has no pool in the language or in the standard library. An array of idle objects is the usual form.
  • JavaScript runs one thread per agent, so the pool needs no lock. A pool shared with workers would need messages or Atomics.
  • Node.js database drivers keep connection pools, and games pool objects to avoid garbage collection pauses during a frame.
TypeScriptGitHub
class Buffer {
  readonly id: number;
  readonly parts: string[] = [];
  constructor(id: number) {
    this.id = id; // a real buffer would be costly to create
  }
  write(text: string): void {
    this.parts.push(text);
  }
  text(): string {
    return this.parts.join(" ");
  }
}

class Pool<T> {
  private readonly idleItems: T[] = [];
  created = 0;
  private readonly create: (n: number) => T;
  private readonly reset: (item: T) => void;
  private readonly maxIdle: number;

  constructor(create: (n: number) => T, reset: (item: T) => void, maxIdle: number) {
    this.create = create;
    this.reset = reset;
    this.maxIdle = maxIdle;
  }

  acquire(): T {
    const item = this.idleItems.pop();
    if (item !== undefined) return item;
    this.created += 1;
    return this.create(this.created);
  }

  release(item: T): void {
    this.reset(item); // clear the state before the next user sees it
    if (this.idleItems.length < this.maxIdle) this.idleItems.push(item);
  }

  use<R>(fn: (item: T) => R): R {
    const item = this.acquire();
    try {
      return fn(item);
    } finally {
      this.release(item); // runs even if fn throws
    }
  }

  get idle(): number {
    return this.idleItems.length;
  }
}

const pool = new Pool<Buffer>((n) => new Buffer(n), (b) => { b.parts.length = 0; }, 2);
for (let i = 1; i <= 3; i++) {
  pool.use((b) => {
    b.write(`request ${i}`);
    console.log(`request ${i} -> buffer #${b.id}: ${b.text()}`);
  });
}

const held: Buffer[] = [pool.acquire(), pool.acquire(), pool.acquire()];
console.log("3 at once -> buffers", held.map((b) => `#${b.id}`).sort().join(" "));
for (const b of held) pool.release(b);
console.log("idle after release:", pool.idle);
console.log("created:", pool.created);
Output
request 1 -> buffer #1: request 1
request 2 -> buffer #1: request 2
request 3 -> buffer #1: request 3
3 at once -> buffers #1 #2 #3
idle after release: 2
created: 3
  • Verdict: idiom. A generic Pool<T> takes the create and reset functions, so one class serves every kind of pooled object.
  • The type T cannot stop a caller from keeping a reference after release. That rule is a convention, not a type check.
package main

import (
	"fmt"
	"slices"
	"strings"
	"sync/atomic"
)

type Buffer struct {
	ID   int // a real buffer would be costly to create
	Text strings.Builder
}

// Pool keeps idle items in a buffered channel, the "leaky buffer" of
// Effective Go. The channel is safe for many goroutines.
type Pool struct {
	idle    chan *Buffer
	created atomic.Int64
}

func NewPool(maxIdle int) *Pool {
	return &Pool{idle: make(chan *Buffer, maxIdle)}
}

func (p *Pool) Acquire() *Buffer {
	select {
	case b := <-p.idle:
		return b
	default: // none idle, so create one
		return &Buffer{ID: int(p.created.Add(1))}
	}
}

func (p *Pool) Release(b *Buffer) {
	b.Text.Reset() // clear the state before the next user sees it
	select {
	case p.idle <- b:
	default: // the pool is full, so drop the item
	}
}

func main() {
	pool := NewPool(2)
	for i := 1; i <= 3; i++ {
		func() {
			b := pool.Acquire()
			defer pool.Release(b) // runs even if the body panics
			fmt.Fprintf(&b.Text, "request %d", i)
			fmt.Printf("request %d -> buffer #%d: %s\n", i, b.ID, b.Text.String())
		}()
	}

	held := []*Buffer{pool.Acquire(), pool.Acquire(), pool.Acquire()}
	ids := []string{}
	for _, b := range held {
		ids = append(ids, fmt.Sprintf("#%d", b.ID))
	}
	slices.Sort(ids)
	fmt.Println("3 at once -> buffers", strings.Join(ids, " "))
	for _, b := range held {
		pool.Release(b)
	}
	fmt.Println("idle after release:", len(pool.idle))
	fmt.Println("created:", pool.created.Load())
}
Output
request 1 -> buffer #1: request 1
request 2 -> buffer #1: request 2
request 3 -> buffer #1: request 3
3 at once -> buffers #1 #2 #3
idle after release: 2
created: 3
  • Verdict: stdlib. sync.Pool is the standard pool, but it may drop any item at any time, so it suits temporary buffers and not a fixed set of costly objects. The example uses a buffered channel, which keeps its items.
  • defer returns the item at the end of the function, as a finally block does.
  • database/sql keeps a pool of connections inside each *sql.DB.
RustGitHub
use std::ops::{Deref, DerefMut};
use std::sync::Mutex;

struct Buffer {
    id: usize, // a real buffer would be costly to create
    text: String,
}

struct Pool {
    idle: Mutex<Vec<Buffer>>,
    created: Mutex<usize>,
    max_idle: usize,
}

// A lease gives access to the item and returns it to the pool when dropped.
struct Lease<'a> {
    pool: &'a Pool,
    item: Option<Buffer>,
}

impl Pool {
    fn new(max_idle: usize) -> Pool {
        Pool { idle: Mutex::new(Vec::new()), created: Mutex::new(0), max_idle }
    }

    fn acquire(&self) -> Lease<'_> {
        let item = self.idle.lock().unwrap().pop().unwrap_or_else(|| {
            let mut n = self.created.lock().unwrap();
            *n += 1;
            Buffer { id: *n, text: String::new() }
        });
        Lease { pool: self, item: Some(item) }
    }

    fn release(&self, mut item: Buffer) {
        item.text.clear(); // clear the state before the next user sees it
        let mut idle = self.idle.lock().unwrap();
        if idle.len() < self.max_idle {
            idle.push(item);
        } // else: item is dropped here, the pool is full
    }
}

impl Drop for Lease<'_> {
    fn drop(&mut self) {
        if let Some(item) = self.item.take() {
            self.pool.release(item);
        }
    }
}

impl Deref for Lease<'_> {
    type Target = Buffer;
    fn deref(&self) -> &Buffer {
        self.item.as_ref().unwrap()
    }
}

impl DerefMut for Lease<'_> {
    fn deref_mut(&mut self) -> &mut Buffer {
        self.item.as_mut().unwrap()
    }
}

fn main() {
    let pool = Pool::new(2);
    for i in 1..=3 {
        let mut b = pool.acquire();
        b.text.push_str(&format!("request {i}"));
        println!("request {i} -> buffer #{}: {}", b.id, b.text);
    } // b goes back to the pool here

    {
        let held: Vec<Lease> = (0..3).map(|_| pool.acquire()).collect();
        let mut ids: Vec<usize> = held.iter().map(|b| b.id).collect();
        ids.sort();
        let ids: Vec<String> = ids.iter().map(|id| format!("#{id}")).collect();
        println!("3 at once -> buffers {}", ids.join(" "));
    } // all three go back here
    println!("idle after release: {}", pool.idle.lock().unwrap().len());
    println!("created: {}", pool.created.lock().unwrap());
}
Output
request 1 -> buffer #1: request 1
request 2 -> buffer #1: request 2
request 3 -> buffer #1: request 3
3 at once -> buffers #1 #2 #3
idle after release: 2
created: 3
  • Verdict: idiom. The standard library has no object pool. A guard type with Drop returns the item when it goes out of scope, and the borrow checker stops the guard from living longer than the pool.
  • The lease owns the item, so no other code can use it while it is out. After the drop, the old lease no longer exists, so use after release is a compile error.
  • Crates give pools for connections and objects, and async runtimes have their own.

Consequences

The main benefit is speed when creation is costly. The pool pays the cost once for each object, not once for each use. A pool also makes the time to get an object predictable, because an idle object is ready at once.1 A pool with a maximum size limits the resources that a program holds, for example the number of connections that a database must accept.

The costs are in the lifetime of the objects. An object from a pool is not new, and an object that a client releases is not gone.

Stale state. The pool must reset each object before the next client gets it. If it does not, one client sees the data of another.1 Here the pool has no reset, and the second request gets the token of the first:

This code runs but gives a wrong answer on purpose.

class Buffer:
    def __init__(self):
        self.parts = []


idle = []


def acquire():
    return idle.pop() if idle else Buffer()


def release(buffer):
    idle.append(buffer)  # no reset


b = acquire()
b.parts.append("token=alice-secret")
release(b)

b = acquire()
b.parts.append("page=2")
print(" ".join(b.parts))
Output
token=alice-secret page=2

The fix is one line in release: clear the parts before the buffer goes back. A reset must cover every field. The Go fmt package clears its argument fields and its buffer before each printer goes back to its pool.5

Leaks. A client that does not release an object takes it from the pool for ever. A pool that creates on demand then grows, and a bounded pool runs out and blocks or fails. The .NET documentation of ArrayPool<T>.Rent says that a buffer that is not returned is not a fatal error, but it can reduce performance, because the pool may create a new buffer to replace it.6 The same page warns that a rented array may not be zero-initialized, which is the stale-state problem again.6

Use after release. A client that keeps a reference after it releases the object can change the object while another client uses it. Most languages cannot stop this. A Rust guard type can, because the guard owns the object.

Memory. Idle objects stay in memory. The ASP.NET Core documentation says that objects managed by a pool are not de-allocated until the pool is de-allocated.3

Variable size. A pool of buffers can keep a very large buffer that one request needed once. The Go fmt package drops a buffer larger than 64 KiB in place of putting it back, so that the entries of its pool keep about the same memory cost.5

When not to use it

Do not pool objects that are cheap to create. The ASP.NET Core documentation says that object pooling does not always improve performance: unless the initialization cost of an object is high, it is usually slower to get the object from the pool. It advises to use object pooling only after collecting performance data from realistic scenarios.3 A modern garbage collector allocates a small object fast, and a pool of such objects only adds a lock and the risk of stale state.

Do not pool an object that a client cannot reset. If the state of the object depends on its past use in ways the pool cannot see, a new object is safer.

Do not write a pool when the platform has one. Database drivers pool connections, and ADO.NET does it behind Open and Close.2 Most standard libraries have a thread pool.

Connection pool. The most common pool. ADO.NET keeps connections in a pool, and a call to Close returns the connection to the pool in place of closing the link to the server.2 A connection pool usually has a maximum size and blocks or fails when it is full.

Thread pool. A pool of worker threads that take tasks from a queue. The thread is the costly object, and the task is the use.

Temporary-object pool. Go's sync.Pool caches allocated but unused items to reduce the pressure on the garbage collector. Any item in it may be removed at any time without notification.7 It suits temporary buffers, and not objects that the program must keep. The Go documentation names the fmt package as a good use: a store of output buffers that grows under load and shrinks when the program is quiet.7

Leaky buffer. Effective Go builds a free list from a buffered channel. A client takes a buffer from the channel if one is there, or allocates a new one. After use, it puts the buffer back if there is room, or drops it.4 The Go example on this page uses this form.

Array pool. .NET's ArrayPool<T> lends arrays of at least a requested length, and the caller should return each array to the same pool.6

Pooling (POSA3). Kircher and Jain describe pooling as a general resource-management pattern, with a family of related patterns for the life of a resource: lazy acquisition, eager acquisition, caching and evictor.8

Flyweight. A Flyweight pattern also shares objects, but its objects are immutable and many clients use one object at the same time. A pooled object is mutable and has one client at a time.

Lazy initialization. A pool that creates objects only on demand applies Lazy initialization to each object. A pool that creates all its objects at the start trades a slower start for a fast first request.

Known uses

  • Go: fmt/print.go at go1.25.0 keeps its printer state in the sync.Pool named ppFree. newPrinter gets a printer from the pool, and free clears its fields, drops a buffer larger than 64 KiB, and puts the printer back.5
  • Apache Commons Pool is a Java library that gives an object-pooling API and several pool implementations.9

References

  1. Object pool pattern, Wikipedia, Introduction; Description; Implementation; Handling of empty pools; Pitfalls
  2. SQL Server Connection Pooling (ADO.NET), Microsoft Learn, Introduction
  3. Object reuse with ObjectPool in ASP.NET Core, Microsoft Learn, Introduction; the note on limits; ObjectPool concepts
  4. Effective Go, A leaky buffer
  5. Go go1.25.0 source, src/fmt/print.go, ppFree, newPrinter and free, lines 146 to 182
  6. ArrayPool<T>.Rent(Int32) Method, .NET API reference, Remarks
  7. Package sync, the Go standard library, type Pool
  8. Michael Kircher and Prashant Jain, Pattern-Oriented Software Architecture, Volume 3, Patterns for Resource Management, Wiley, 2004, Chapter 3, Resource Lifecycle, Pooling
  9. Apache Commons Pool, The Commons Pool

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/CAQSKE/text.yaml