VOOZH about

URL: https://deepwiki.com/hypervel/object-pool/4.1-recycle-strategies

⇱ Recycle Strategies | hypervel/object-pool | DeepWiki


Loading...
Menu

Recycle Strategies

Purpose and Scope

This document covers the strategy pattern implementation used for automated pool recycling in the hypervel/object-pool package. Recycle strategies determine when and how idle objects in a pool should be flushed to prevent resource staleness and memory buildup. The document focuses on the RecycleStrategy interface and its implementations, particularly the built-in TimeStrategy.

For information about the automated scheduler that applies these strategies to pools, see Object Recycler. For details on pool configuration options that affect recycling behavior, see Pool Configuration.


Strategy Pattern Overview

The recycling subsystem uses the strategy pattern to decouple recycling logic from the core pool implementation. Each ObjectPool instance can have its own recycling strategy that determines when objects should be flushed from the pool.


Sources: src/Contracts/RecycleStrategy.php1-21 src/Contracts/TimeStrategy.php1-14 src/Strategies/TimeStrategy.php1-64


RecycleStrategy Interface

The RecycleStrategy interface defines the contract that all recycling strategies must implement. It consists of two methods that work together to manage the recycling lifecycle.

Interface Definition

MethodReturn TypeDescription
shouldRecycle(ObjectPool $pool)boolDetermines if the pool should recycle objects at this moment
recycle(ObjectPool $pool)voidPerforms the actual recycling operation on the pool

The interface is located at src/Contracts/RecycleStrategy.php9-20 and is designed to be simple yet flexible, allowing different implementations to use various criteria for recycling decisions.

Decision and Execution Flow


Sources: src/Contracts/RecycleStrategy.php11-19 src/Strategies/TimeStrategy.php33-54


TimeStrategy Interface

The TimeStrategy interface extends RecycleStrategy to provide time-based recycling semantics. It adds one additional method for querying the recycling interval.

Interface Definition

Located at src/Contracts/TimeStrategy.php7-13 the interface adds:

MethodReturn TypeDescription
getRecycleInterval()floatReturns the time interval (in seconds) between recycling operations

This interface enables the recycler to coordinate the strategy's timing expectations with the scheduler's execution interval.

Sources: src/Contracts/TimeStrategy.php1-14


TimeStrategy Implementation

The concrete TimeStrategy class located at src/Strategies/TimeStrategy.php1-64 implements time-based recycling using timestamps and configurable intervals.

Class Structure


Sources: src/Strategies/TimeStrategy.php14-28

Constructor and Initialization

The strategy is initialized through dependency injection at src/Strategies/TimeStrategy.php24-28:

  • Receives a ContainerInterface instance
  • Retrieves the global recycler interval from the Recycler instance
  • Stores the interval in the recycleInterval property for efficient access

This design allows the strategy to align its timing expectations with the global recycler's execution schedule.

Sources: src/Strategies/TimeStrategy.php24-28

shouldRecycle Implementation

The shouldRecycle() method at src/Strategies/TimeStrategy.php33-41 implements time-based decision logic:


Algorithm details:

  1. Retrieves lastRecycledAt timestamp from the pool
  2. Converts DateTime objects to Unix timestamps, defaults to 0 if null
  3. Calculates elapsed time: Carbon::now()->timestamp - timestamp
  4. Returns true if elapsed time exceeds recycleInterval

Sources: src/Strategies/TimeStrategy.php33-41

recycle Implementation

The recycle() method at src/Strategies/TimeStrategy.php46-54 performs the actual object flushing:

StepOperationCode Reference
1. Calculate countrecycleCount = floor(recycleRatio × objectsInPool)src/Strategies/TimeStrategy.php48
2. Flush objectsLoop recycleCount times calling flushOne()src/Strategies/TimeStrategy.php49-51
3. Update timestampSet lastRecycledAt to current timesrc/Strategies/TimeStrategy.php53

Key configuration dependency:

  • The recycleRatio is obtained from the pool's PoolOption configuration
  • This ratio determines what percentage of idle objects to flush (e.g., 0.5 = 50%)

Sources: src/Strategies/TimeStrategy.php46-54


Custom Strategy Implementation

To implement a custom recycling strategy, create a class that implements the RecycleStrategy interface. The following table outlines common use cases:

Strategy TypeshouldRecycle Logicrecycle LogicUse Case
Time-basedCheck elapsed timeFlush percentage of objectsPeriodic maintenance (default)
Usage-basedCheck object access countFlush least-used objectsHigh-traffic pools
Health-basedCheck object validationFlush failed objectsConnection pools with health checks
Memory-basedCheck memory usageFlush until under thresholdResource-constrained environments
HybridMultiple conditions (AND/OR)Combined flush strategiesComplex requirements

Implementation Pattern


Important considerations:

  1. Thread safety: Strategies execute in the recycler's coroutine context
  2. Performance: Keep shouldRecycle() lightweight as it's called frequently
  3. State management: Store state in the strategy instance or use pool methods
  4. Timestamp tracking: Always update lastRecycledAt after recycling

Sources: src/Contracts/RecycleStrategy.php9-20


Integration with ObjectPool

Each ObjectPool instance maintains its recycling state and exposes methods for strategies to interact with:

Pool State Management


Available Pool Methods

MethodPurposeUsed By
getLastRecycledAt(): ?DateTimeGet timestamp of last recycle operationshouldRecycle()
setLastRecycledAt(DateTime $time): voidUpdate last recycled timestamprecycle()
getOption(): PoolOptionAccess pool configurationBoth methods
getObjectNumberInPool(): intGet count of idle objectsrecycle()
flushOne(): voidFlush a single object from poolrecycle()
flush(): voidFlush all objects from poolCustom strategies

Sources: src/Strategies/TimeStrategy.php33-54


Configuration Dependencies

Recycle strategies depend on several configuration parameters from PoolOption:

ConfigurationTypeDefaultImpact on Recycling
recycleRatiofloat0.5Percentage of objects to flush (TimeStrategy)
Custom propertiesvariesvariesAvailable through getOption() for custom strategies

The global recycler interval (separate from PoolOption) controls how frequently the ObjectRecycler evaluates strategies. This interval is accessed at src/Strategies/TimeStrategy.php27 through the Recycler contract.

Sources: src/Strategies/TimeStrategy.php27-28 src/Strategies/TimeStrategy.php48


Lifecycle and Event Flow

The complete lifecycle showing how strategies integrate with the broader recycling system:


Sources: src/Listeners/StartRecycler.php26-30 src/Strategies/TimeStrategy.php33-54