VLink  2.0.0
A high-performance communication middleware
object_pool.h File Reference

Thread-safe generic object pool with RAII handles and a tunable reset policy. More...

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

Go to the source code of this file.

Classes

class  vlink::ObjectPoolBase
 Type-independent base of ObjectPool that owns counters, mutex and policy state. More...
 
struct  vlink::ObjectPoolBase::Stats
 Point-in-time snapshot of internal pool counters. More...
 
class  vlink::ObjectPool< T >
 Thread-safe recycling pool for instances of T with RAII acquisition. More...
 
struct  vlink::ObjectPool< T >::PoolDeleter
 Custom deleter installed on every RAII handle handed out by get / get_shared. More...
 

Namespaces

 

Detailed Description

Thread-safe generic object pool with RAII handles and a tunable reset policy.

ObjectPool<T> recycles previously allocated T instances so that hot paths avoid repeated heap traffic. Callers acquire an object through one of three entry points, use it, and then either let RAII return it automatically or hand it back manually.

Acquisition variants:

Method Returned handle Returns to pool automatically
get() unique_ptr<T, PoolDeleter> Yes, on unique_ptr destruction
get_shared shared_ptr<T> Yes, on last shared_ptr release
borrow() Raw T* No, caller must invoke give_back

Reset-policy decision table for the optional ResetCallback:

Policy Reset on acquire Reset on release Typical use
kPolicyNone No No Pure / stateless objects
kPolicyRelease No Yes Default; scrub on the return path
kPolicyAcquire Yes No Scrub right before use
kPolicyBoth Yes Yes Defence-in-depth scrubbing

Lifecycle of a pooled object:

*   factory ---> free list <----------+
*                  |  acquire         |
*                  v                  |
*               in use ---> release --+   (reset on release if enabled)
*                  ^                  |
*                  +--reset-on-acquire+
* 
Thread safety
Every public method acquires the internal mutex so concurrent callers may interleave freely. Factory and reset callbacks run outside the mutex.
Example
auto pool = std::make_shared<vlink::ObjectPool<Buffer>>(
[]{ return std::make_unique<Buffer>(4096); },
4,
16,
[](Buffer& buf){ buf.clear(); },
{
auto buf = pool->get();
buf->write(payload.data(), payload.size());
}
Buffer* raw = pool->borrow();
raw->write(payload.data(), payload.size());
pool->give_back(raw);