---
id: wiki-2026-0508-resource-management
title: Resource Management
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [RAII, Resource Acquisition, Lifecycle Management]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [systems, memory, concurrency, raii, lifecycle]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: Rust/TypeScript/Python
  framework: tokio/Node/asyncio
---

# Resource Management

## 매 한 줄
> **"매 acquire/release 의 pairing 을 lexical scope 에 강제"**. 매 file handle, socket, mutex, GPU buffer, DB connection 등 finite resource 의 leak 을 방지하는 discipline. Stroustrup 의 RAII (1980s C++) → Rust 의 ownership/Drop (2015) → Python `with` / Java try-with-resources / TS `using` (TC39 Stage 3, 2023) 으로 mainstream language 전반에 확산.

## 매 핵심

### 매 resource 종류
- **Memory**: heap allocation, buffer, arena.
- **Handles**: file, socket, pipe, FD limit (Linux 기본 1024).
- **Locks**: mutex, rwlock, semaphore, distributed lock (Redis/etcd).
- **Connections**: DB pool, HTTP keep-alive, gRPC channel.
- **GPU/Accelerator**: VRAM buffer, CUDA stream, MLX array.

### 매 acquire/release 패턴
- **RAII**: ctor acquire, dtor release — C++/Rust.
- **try-with-resources**: lexical block — Java/Python/TS `using`.
- **Defer**: stack-of-callbacks — Go, Zig.
- **Linear types**: compile-time use-once — Rust ownership, Haskell linear.

### 매 응용
1. Connection pool: max_size + idle timeout + acquire timeout.
2. Bounded concurrency: semaphore 로 N parallel limit.
3. Cleanup ordering: LIFO (stack) — dependent resource 먼저 release.

## 💻 패턴

### Rust: RAII via Drop
```rust
use std::fs::File;
use std::io::Write;

fn write_log(msg: &str) -> std::io::Result<()> {
    let mut f = File::create("/tmp/log.txt")?; // acquire
    f.write_all(msg.as_bytes())?;
    Ok(()) // f.drop() automatic — release on scope exit, even on panic
}
```

### TypeScript: `using` (TC39 explicit resource management, ES2024)
```typescript
class DbConnection implements Disposable {
  constructor(public readonly url: string) { /* connect */ }
  query(sql: string) { /* ... */ }
  [Symbol.dispose]() { /* close */ }
}

function fetchUser(id: string) {
  using db = new DbConnection('postgres://...');
  return db.query(`select * from users where id='${id}'`);
} // db disposed automatically on return / throw
```

### Python: contextmanager
```python
from contextlib import contextmanager
import psycopg

@contextmanager
def connection(dsn: str):
    conn = psycopg.connect(dsn)
    try:
        yield conn
    finally:
        conn.close()

with connection('postgres://...') as c:
    c.execute('SELECT 1')
# c is closed even if execute raises
```

### Go: defer (LIFO)
```go
func processFile(path string) error {
    f, err := os.Open(path)
    if err != nil { return err }
    defer f.Close() // LIFO — runs even on panic

    lock := acquireLock()
    defer lock.Release()

    return parse(f)
}
```

### Connection pool (Node + pg)
```typescript
import { Pool } from 'pg';

const pool = new Pool({
  max: 20,
  idleTimeoutMillis: 30_000,
  connectionTimeoutMillis: 2_000,
});

async function getUser(id: string) {
  const client = await pool.connect();
  try {
    const r = await client.query('SELECT * FROM users WHERE id=$1', [id]);
    return r.rows[0];
  } finally {
    client.release(); // 매 finally 가 critical
  }
}
```

### Bounded concurrency (semaphore)
```typescript
import pLimit from 'p-limit';

const limit = pLimit(10); // max 10 concurrent
const results = await Promise.all(
  urls.map(url => limit(() => fetch(url).then(r => r.json()))),
);
```

### MLX GPU buffer (Apple Silicon, 2026)
```python
import mlx.core as mx

def process_batch(x: mx.array) -> mx.array:
    # MLX uses unified memory; explicit eval boundaries
    y = mx.matmul(x, x.T)
    mx.eval(y)  # force materialization, release lazy graph
    return y
```

### AsyncIO timeout + cancel
```python
import asyncio

async def fetch_with_timeout():
    async with asyncio.timeout(5.0):
        async with aiohttp.ClientSession() as s:
            async with s.get('https://api.example.com') as r:
                return await r.json()
    # all three context managers cleanly close on timeout
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| Rust/C++ | RAII via Drop/destructor (default) |
| TS/JS modern | `using` + Disposable (TC39 explicit) |
| Python | `with` + contextlib |
| Go | defer (LIFO ordering) |
| Network connection 다수 | Pool + acquire timeout |
| Concurrent task 수천 | Semaphore (p-limit, asyncio.Semaphore) |
| GPU memory | Explicit eval / del / cudaFree |

**기본값**: 매 lexical scope 기반 (RAII / using / with / defer). 매 manual close 의 X.

## 🔗 Graph
- 부모: [[Concurrency]]
- 변형: [[RAII]]
- 응용: [[Memory Management]] · [[Graceful Shutdown]]
- Adjacent: [[Error Handling]] · [[Async Programming]] · [[Garbage Collection]]

## 🤖 LLM 활용
**언제**: 매 server, 매 batch job, 매 GPU inference, 매 long-running daemon — 매 leak 누적이 critical.
**언제 X**: 매 short-lived script (<1s), 매 throwaway notebook — 매 process exit 이 cleanup.

## ❌ 안티패턴
- **Forgotten close**: 매 try 만, 매 finally 없음 → leak on exception.
- **Double-free**: 매 close 두 번 → undefined behavior 또는 exception.
- **Use-after-release**: 매 closed connection 재사용 → broken pipe.
- **Manual ref counting in GC language**: 매 reinventing — `using`/`with` 사용.
- **Unbounded pool**: 매 max 없음 → DB connection storm 으로 outage.
- **GPU OOM 무시**: 매 eval 없이 lazy graph 누적 → MLX/CUDA OOM.

## 🧪 검증 / 중복
- Verified: Stroustrup *The C++ Programming Language*; Rust *Programming Rust* 2e; TC39 Explicit Resource Management proposal (Stage 3, 2024).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — RAII/using/with/defer patterns + pooling + GPU |
