---
name: double-checked-locking
description: This skill should be used when the user asks about "double checked locking pattern", "when to use double checked locking", "lazy initialization thread safe", "singleton thread safe", "reduce lock overhead", or mentions needing to optimize synchronization for initialization.
version: 1.0.0
---

# Double-Checked Locking Pattern

## What Is It
Double-Checked Locking reduces the overhead of acquiring a lock by first testing the condition without synchronization, and only acquiring the lock if the check indicates that the action is needed. A second check is performed inside the lock.

## When to Use
- **Lazy singletons** - Thread-safe singleton initialization
- **Resource initialization** - One-time expensive setup
- **Configuration loading** - Load config on first access
- **Connection pools** - Initialize pool on first use
- **Caching** - Populate cache on first miss

## When NOT to Use
- **Simple initialization** - Eager init or simple lock is clearer
- **Languages with better alternatives** - Use `async lazy` or `once` primitives
- **Performance not critical** - Regular locking is simpler
- **Modern JS/TS** - Module singletons are simpler

## How to Implement

### Implementation Steps
1. Check condition without lock (first check)
2. If condition not met, acquire lock
3. Check condition again inside lock (second check)
4. Perform initialization if still needed
5. Release lock

### TypeScript Implementation

```typescript
class LazySingleton {
  private static instance: LazySingleton | null = null;
  private static lock = new Lock();

  static getInstance(): LazySingleton {
    // First check (no lock)
    if (!this.instance) {
      this.lock.acquire();
      try {
        // Second check (with lock)
        if (!this.instance) {
          this.instance = new LazySingleton();
        }
      } finally {
        this.lock.release();
      }
    }
    return this.instance;
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/double-checked-locking.ts` - Basic implementation with singleton
- `examples/double-checked-locking-advanced.ts` - Real-world example with resource pool

## Related Patterns
- **Singleton** - DCL is often used for thread-safe singletons
- **Lazy Initialization** - DCL is a thread-safe lazy init
- **Object Pool** - Can use DCL for pool initialization
