---
name: object-pool
description: This skill should be used when the user asks about "object pool pattern", "pool objects", "reuse objects", "recycle objects", "expensive initialization", or mentions managing expensive-to-create objects.
version: 1.0.0
---

# Object Pool Pattern

## What Is It
Object Pool manages a set of reusable objects. Instead of creating and destroying objects, clients borrow from the pool and return them when done, avoiding expensive initialization.

## When to Use
- **Expensive creation** - Database connections, threads
- **High frequency usage** - Many create/destroy cycles
- **Resource limited** - Finite expensive resources
- **Performance critical** - Allocation overhead matters

## When NOT to Use
- **Cheap objects** - Simple POJOs, primitives
- **Stateful objects** - Complex reset logic needed
- **Variable demand** - Unpredictable usage spikes
- **Memory constrained** - Pool holds unused objects

## How to Implement

```typescript
class ObjectPool<T> {
  private available: T[] = [];
  private inUse = new Set<T>();

  constructor(
    private factory: () => T,
    private reset: (obj: T) => void,
    initialSize: number = 0
  ) {
    for (let i = 0; i < initialSize; i++) {
      this.available.push(this.factory());
    }
  }

  acquire(): T {
    let obj = this.available.pop();
    if (!obj) {
      obj = this.factory();
    }
    this.inUse.add(obj);
    return obj;
  }

  release(obj: T): void {
    if (this.inUse.has(obj)) {
      this.inUse.delete(obj);
      this.reset(obj);
      this.available.push(obj);
    }
  }
}
```

## Code Examples
- `examples/object-pool.ts` - Basic implementation
- `examples/object-pool-advanced.ts` - Real-world usage

## Related Patterns
- **Factory Method** - Pool uses factory to create
- **Singleton** - Pool often singleton
- **Flyweight** - Both share/reuse objects
