Files
2nd/10_Wiki/Topics/Architecture/Resource-Management.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

6.0 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-resource-management Resource Management 10_Wiki/Topics verified self
RAII
Resource Acquisition
Lifecycle Management
none A 0.9 applied
systems
memory
concurrency
raii
lifecycle
2026-05-10 pending
language framework
Rust/TypeScript/Python 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

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)

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

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)

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)

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)

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)

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

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

🤖 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