VLink 2.0.0
A high-performance communication middleware
Loading...
Searching...
No Matches
object_pool.h File Reference

Thread-safe generic object pool with configurable reset policy and RAII ownership. More...

#include <functional>
#include <memory>
#include <mutex>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <vector>
#include "./macros.h"
Include dependency graph for object_pool.h:

Go to the source code of this file.

Classes

 Thread-safe object pool for type T with RAII acquisition and configurable reset policy. More...
 Snapshot of pool statistics at a point in time. More...
 Custom deleter for RAII handles returned by get() and get_shared(). More...

Namespaces

Detailed Description

Thread-safe generic object pool with configurable reset policy and RAII ownership.

ObjectPool<T> maintains a free-list of pre-allocated T objects. Callers acquire an object, use it, then return it to the pool automatically (RAII) or manually. Objects are recycled rather than destroyed, reducing heap pressure in hot paths.

Acquisition API:

Method Return type Auto-return on destruction
get() unique_ptr<T, PoolDeleter> Yes (via PoolDeleter)
get_shared shared_ptr<T> (PoolDeleter) Yes (via shared_ptr deleter)
borrow() T* (raw pointer) No – caller must call give_back()

Reset policy controls when the optional ResetCallback is invoked:

Policy Reset on acquire Reset on release Use case
kPolicyNone No No Immutable / stateless objects
kPolicyRelease No Yes Clean before returning (default)
kPolicyAcquire Yes No Clean before use
kPolicyBoth Yes Yes Clean on both sides
Thread safety
All public methods are protected by an internal mutex and are safe to call concurrently.
Note
  • When max_size is 0 (default), the pool grows without bound.
  • When the pool is exhausted (max_size > 0 and the number of live objects reaches max_size), get(), get_shared(), and borrow() throw std::runtime_error.
  • If FactoryCallback returns nullptr, a std::runtime_error is thrown.
Example
auto pool = std::make_shared<vlink::ObjectPool<Buffer>>(
[]{ return std::make_unique<Buffer>(4096); }, // factory
4, // initial_size
16, // max_size
[](Buffer& b){ b.reset(); }, // reset callback
);
{
auto buf = pool->get(); // auto-returned when buf goes out of scope
buf->write(data, len);
}
// Manual acquire/release:
Buffer* raw = pool->borrow();
raw->write(data, len);
pool->give_back(raw);
Template Parameters
TType of objects managed by the pool.