VOOZH about

URL: https://deepwiki.com/hypervel/object-pool/2.1-object-pool-implementation

⇱ Object Pool Implementation | hypervel/object-pool | DeepWiki


Loading...
Menu

Object Pool Implementation

Purpose and Scope

This document provides a comprehensive technical reference for the ObjectPool abstract class, which serves as the foundational component for managing reusable object lifecycles in the hypervel/object-pool package. The ObjectPool class defines the core pooling behavior including object acquisition, release, lifetime management, and recycling integration.

This page focuses specifically on the abstract ObjectPool class located in src/ObjectPool.php For information about:

Sources: src/ObjectPool.php1-330 src/Contracts/ObjectPool.php1-62


Architecture Overview

The ObjectPool class is an abstract generic class that implements the ObjectPoolContract interface. It uses PHP generics annotation (@template T of object) to provide type safety for pooled objects.

Class Structure


The ObjectPool class defines one abstract method that concrete implementations must provide:

MethodSignaturePurpose
createObject()protected function createObject(): objectFactory method for creating new pooled objects

Sources: src/ObjectPool.php22-330 src/Contracts/ObjectPool.php10-61 src/PoolOption.php9-138


Core Properties

The ObjectPool maintains several critical instance variables to manage pool state:

State Management Properties

PropertyTypePurposeInitialized
$channelChannelCoroutine-safe storage for available objectsConstructor
$optionPoolOptionPool configuration parametersConstructor
$currentObjectNumberintTotal count of objects managed by pool (in use + available)0
$creationTimestampsarrayMaps spl_object_hash() to creation timestamp (microtime)[]
$destroyCallbackClosureCustom cleanup logic executed when objects are destroyedfn () => null
$recycleStrategyRecycleStrategy|nullLazy-loaded strategy instance for automated recyclingnull
$lastRecycledAtDateTime|int|nullTimestamp of last recycling operationnull
$containerContainerInterfacePSR-11 dependency injection containerConstructor parameter

Property Relationships


Sources: src/ObjectPool.php24-63


Object Lifecycle Operations

The ObjectPool implements a complete lifecycle for managed objects through three primary operations: acquisition, release, and flushing.

Acquisition Flow

The get() method retrieves objects from the pool and enforces lifetime policies:


Key Implementation Details:

  1. Object Creation Path src/ObjectPool.php204-210: When the pool is empty and below maxObjects, a new object is created via the abstract createObject() method, the counter is incremented, and the creation timestamp is recorded.

  2. Object Retrieval Path src/ObjectPool.php216-219: Objects are popped from the channel with a configurable waitTimeout. If the timeout expires, a RuntimeException is thrown.

  3. Lifetime Validation src/ObjectPool.php81-92: After retrieval, if maxLifetime is configured, the object is checked for expiration. Expired objects are destroyed and replaced with fresh ones.

Sources: src/ObjectPool.php77-93 src/ObjectPool.php199-222 src/ObjectPool.php239-248

Release Mechanism

The release() method returns objects to the pool for reuse:


The implementation is straightforward src/ObjectPool.php98-101: the object is pushed back into the channel. The currentObjectNumber and creation timestamp remain unchanged, allowing the object to be reused by subsequent get() calls.

Sources: src/ObjectPool.php98-101

Flush Operations

The pool provides two flushing mechanisms for removing excess objects:

Full Flush

The flush() method reduces the pool to its minimum size src/ObjectPool.php106-122:


The flush operation:

  1. Captures the current number of objects in the pool
  2. Iterates while currentObjectNumber > minObjects and objects are available
  3. Pops objects with a minimal timeout (0.001s)
  4. Destroys each retrieved object
  5. Stops when reaching minObjects or the initial count is exhausted

Single Object Flush

The flushOne() method removes a single object if conditions are met src/ObjectPool.php127-146:

ConditionAction
currentObjectNumber <= minObjectsReturn immediately (preserve minimum)
Pool is emptyReturn immediately
Object retrieval failsReturn immediately
force = trueDestroy the object unconditionally
Object exceeds maxLifetimeDestroy the object
OtherwiseRelease the object back to pool

Sources: src/ObjectPool.php106-122 src/ObjectPool.php127-146


Lifetime Tracking System

The ObjectPool implements precise lifetime tracking using microsecond timestamps to enforce maxLifetime policies.

Timestamp Storage

The creationTimestamps array maps object identities to creation times src/ObjectPool.php42:


When an object is created, its timestamp is recorded src/ObjectPool.php207:


Lifetime Validation Logic


The exceedsMaxLifetime() method src/ObjectPool.php239-248 performs the following checks:

  1. Returns false if maxLifetime is not configured (0 or null)
  2. Retrieves the creation timestamp using spl_object_hash($object) as the key
  3. Compares current time to creationTime + maxLifetime
  4. Returns true if the object has exceeded its allowed lifetime

Timestamp Cleanup

When objects are destroyed src/ObjectPool.php263 their timestamps are removed to prevent memory leaks:


Sources: src/ObjectPool.php42 src/ObjectPool.php207 src/ObjectPool.php239-248 src/ObjectPool.php263


Configuration Integration

The ObjectPool integrates with the PoolOption class for configuration management. The configuration is initialized during construction via the initOption() method src/ObjectPool.php175-185

Configuration Parameters Mapping

Configuration KeyPoolOption PropertyDefault ValuePurpose
min_objectsminObjects1Minimum pool size maintained by recycling
max_objectsmaxObjects10Maximum number of objects that can be created
wait_timeoutwaitTimeout3.0Seconds to wait for an object when pool is exhausted
max_lifetimemaxLifetime60.0Seconds before an object is considered expired
recycle_ratiorecycleRatio0.2Fraction of objects to recycle (unused by ObjectPool directly)
recycle_strategyrecycleStrategyTimeStrategy::classFully-qualified class name of recycling strategy

Configuration Usage Throughout ObjectPool


The option property is accessible via getOption() src/ObjectPool.php159-162 allowing external components to inspect configuration at runtime.

Sources: src/ObjectPool.php32 src/ObjectPool.php66-70 src/ObjectPool.php175-185 src/PoolOption.php21-29


Destruction Callbacks

The ObjectPool provides a hook for custom cleanup logic when objects are destroyed. This is implemented through the destroyCallback closure property.

Default Behavior

The destroy callback is initialized as a no-op src/ObjectPool.php67:


Setting Custom Callbacks

Consumers can register custom cleanup logic using setDestroyCallback() src/ObjectPool.php270-275:


The method returns static for method chaining.

Callback Execution

The callback is invoked within destroyObject() src/ObjectPool.php253-265 with error handling:


Key Points:

  1. Error Isolation: Exceptions in the callback are caught and logged, but do not prevent cleanup
  2. Guaranteed Cleanup: The finally block ensures currentObjectNumber is decremented and timestamps are removed
  3. Optional Logging: If StdoutLoggerInterface is available in the container, exceptions are logged

Sources: src/ObjectPool.php47 src/ObjectPool.php67 src/ObjectPool.php253-265 src/ObjectPool.php270-275


Recycling Integration

The ObjectPool integrates with the automated recycling subsystem through two properties: recycleStrategy and lastRecycledAt. For details on the recycling subsystem, see Object Recycling.

Strategy Management

The recycle strategy is lazy-loaded from the container src/ObjectPool.php292-300:


The strategy class name is stored in PoolOption and defaults to TimeStrategy::class. Strategies can be changed at runtime using setRecycleStrategy() src/ObjectPool.php305-311:


Last Recycled Timestamp

The lastRecycledAt property tracks when the pool was last recycled src/ObjectPool.php57:


This property is managed by the ObjectRecycler component (see Object Recycler) and can be accessed via:

Sources: src/ObjectPool.php52 src/ObjectPool.php57 src/ObjectPool.php292-311 src/ObjectPool.php316-329


Statistics and Monitoring

The getStats() method provides runtime visibility into pool state src/ObjectPool.php280-287:


Statistics Output

KeyValueDescription
objects_countintTotal objects managed by pool (in use + available)
objects_in_poolintObjects currently available in channel
last_recycled_atDateTime|int|nullTimestamp of last recycling operation

Derived Metrics

From the statistics, the following can be calculated:

Objects In Use = objects_count - objects_in_pool
Pool Utilization = (objects_count - objects_in_pool) / max_objects
Pool Availability = objects_in_pool / objects_count

Direct Access Methods

For real-time queries, the following methods provide direct access:

MethodReturnsSource
getCurrentObjectNumber()intsrc/ObjectPool.php151-154
getObjectNumberInPool()intsrc/ObjectPool.php167-170

The getObjectNumberInPool() method delegates to $this->channel->length() for accurate real-time counts.

Sources: src/ObjectPool.php151-154 src/ObjectPool.php167-170 src/ObjectPool.php280-287


Implementation Requirements

Concrete classes extending ObjectPool must implement the abstract createObject() method:


Implementation Contract

AspectRequirement
Return TypeMust return an object instance
ExceptionsAny thrown exception is caught in getObject() src/ObjectPool.php211-214 and results in currentObjectNumber being decremented
IdempotencyEach call should create a new independent object
Thread SafetyMust be safe to call from multiple coroutines

Example Implementations

The package provides SimpleObjectPool src/SimpleObjectPool.php as a reference implementation that uses a callback:


For details, see SimpleObjectPool.

Sources: src/ObjectPool.php192 src/ObjectPool.php199-214


Related Components

The ObjectPool class collaborates with several other components in the system:

Direct Dependencies

ComponentRelationshipPurpose
ChannelCompositionStores available objects with coroutine safety
PoolOptionCompositionProvides configuration parameters
ContainerInterfaceDependencyResolves recycle strategies and logger
RecycleStrategyAssociationDetermines when/how to recycle objects

Related Pages

Sources: src/ObjectPool.php1-330

Refresh this wiki

On this page