[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,95 +2,177 @@
|
||||
id: wiki-2026-0508-마크-스윕-mark-sweep
|
||||
title: 마크 스윕(Mark Sweep)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-A62B31]
|
||||
aliases: [Mark-Sweep, Mark and Sweep, Tracing GC]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [gc, memory, runtime, algorithm, jvm, v8]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - 마크-스윕([[Mark-Sweep]])"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: C/C++/Java
|
||||
framework: JVM/V8/Go runtime
|
||||
---
|
||||
|
||||
# [[마크-스윕(Mark-Sweep)]]
|
||||
# 마크 스윕(Mark Sweep)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 마크-스윕(Mark-Sweep)은 V8 엔진 및 자바 가상 머신(JVM) 등에서 더 이상 필요하지 않은 객체의 메모리를 회수하기 위해 사용하는 주요 가비지 컬렉션([[Major GC]]) 알고리즘입니다 [1-3]. 이 알고리즘은 힙을 순회하며 활성 상태인 객체를 식별하는 '마크(Mark)' 단계와, 표시되지 않은 객체를 제거하여 메모리를 확보하는 '스윕(Sweep)' 단계로 나뉘어 동작합니다 [2, 4, 5]. 주로 수십에서 수백 메가바이트의 데이터를 포함할 수 있는 대용량 메모리 영역인 구공간([[Old Space]])을 관리하는 데 필수적으로 사용됩니다 [4, 6].
|
||||
## 매 한 줄
|
||||
> **"매 root 에서 reachable 한 것만 매 mark, 매 unmarked 는 매 sweep"**. 매 1960 McCarthy 의 LISP 가 매 origin, 매 60+ 년 동안 매 tracing GC 의 backbone. 매 modern 변형 (G1, ZGC, Shenandoah, V8 Orinoco) 매 모두 매 mark-sweep 의 evolution.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
**알고리즘의 주요 동작 단계**
|
||||
* **마크(Mark) 단계:** 가비지 컬렉터가 스택 포인터와 같은 GC 루트(Root)에서 시작하여 포인터로 연결된 객체 그래프를 깊이 우선 탐색(DFS) 방식으로 재귀적으로 순회합니다 [6, 7]. 이 과정을 통해 도달 가능한(Reachable) 객체, 즉 현재 사용 중인 객체는 활성 상태로 식별되어 마크됩니다 [2, 5, 6, 8]. V8의 마크 단계는 객체의 상태를 미발견 상태인 '백색(White)', 발견되었으나 이웃 객체가 아직 처리되지 않은 '회색(Grey)', 그리고 이웃까지 완전히 처리된 '흑색(Black)'으로 분류하는 삼색(Tri-color) 마킹 시스템을 사용합니다 [6, 9].
|
||||
* **스윕(Sweep) 단계:** 마크 단계가 완료된 후, 가비지 컬렉터는 힙의 마킹 비트맵을 스캔하여 활성 상태로 흑색 표시가 되지 않은(즉, 백색으로 남은) 객체들의 연속된 범위를 찾습니다 [5, 6, 10, 11]. 이렇게 발견된 사용 불가능한 객체들의 메모리 주소는 여유 공간(Free space)으로 변환되어 빈 목록(Free list)에 추가되며, 이후 새로운 객체를 할당할 때 재사용됩니다 [6, 10, 11].
|
||||
## 매 핵심
|
||||
|
||||
**V8 엔진에서의 활용 및 성능 최적화**
|
||||
* **구공간(Old Space) 관리:** 신공간(New Space)을 관리하는 스캐빈지([[Scavenge]]) 알고리즘은 소규모 메모리 수집에는 빠르지만 전체 메모리의 두 배 공간을 필요로 하는 오버헤드가 있어 대용량 힙에는 부적합합니다 [4, 6]. 따라서 V8은 수명이 긴 객체들이 모여 있는 구공간을 수집할 때 마크-스윕 또는 객체를 한곳으로 모으는 과정이 추가된 마크-컴팩트(Mark-Compact) 알고리즘을 사용합니다 [4, 6, 12].
|
||||
* **동시성 및 점진적 처리 기법:** 전통적인 마크-스윕 방식은 실행 중인 애플리케이션의 메인 스레드를 장시간 멈추게 하는([[Stop-the-world]]) 문제가 있습니다 [13, 14]. V8은 이러한 지연 현상을 줄이기 위해 마킹 작업을 여러 번의 짧은 멈춤으로 나누어 수행하는 점진적 마킹([[Incremental Marking]]), 백그라운드 헬퍼 스레드를 활용하여 메인 스레드에 영향을 주지 않는 동시적(Concurrent) 마킹 및 스윕, 그리고 필요할 때까지 메모리 해제를 미루는 지연 스윕(Lazy sweeping) 기법을 도입해 성능을 최적화했습니다 [13-16].
|
||||
### 매 두 phase
|
||||
1. **매 Mark**: 매 root (stack, register, global) 에서 매 reachable graph 매 traverse, 매 mark bit 설정.
|
||||
2. **매 Sweep**: 매 heap 전체를 매 scan, 매 unmarked block 을 매 free list 로.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 vs 친척들
|
||||
- **매 vs Reference Counting**: 매 cycle 처리 가능, 매 thoughput ↑, 매 latency spike ↑.
|
||||
- **매 vs Copying (Cheney)**: 매 fragmentation 발생, 매 메모리 효율 ↑ (매 copy 가 1/2 reserve X).
|
||||
- **매 vs Mark-Compact**: 매 sweep 후 compact 추가 — 매 fragmentation 해결.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** 가비지 컬렉션([[Garbage Collection]]), 구공간(Old Space), 마크-컴팩트(Mark-Compact), [[점진적 마킹(Incremental Marking)]], 스캐빈지(Scavenge)
|
||||
- **Projects/Contexts:** V8 엔진([[V8 Engine]]), 오리노코([[Orinoco]]), [[자바 가상 머신(JVM)]]
|
||||
- **Contradictions/Notes:** 소스의 설명에 따르면, 스캐빈지(Scavenge) 알고리즘은 투-스페이스(to-space)와 프롬-스페이스(from-space)를 사용하는 물리적 메모리 오버헤드가 크기 때문에 신공간(New Space)에서만 유용하게 쓰이며, 반면 마크-스윕은 메모리 오버헤드는 적지만 실행 시간이 오래 걸릴 수 있어 구공간(Old Space) 관리에 사용된다는 명확한 역할 분담이 존재합니다 [4, 6].
|
||||
### 매 Tri-color abstraction
|
||||
- **매 White**: 매 unvisited (sweep 대상).
|
||||
- **매 Grey**: 매 reachable, 매 children 미 traverse.
|
||||
- **매 Black**: 매 reachable + 매 children traversed.
|
||||
- 매 invariant: 매 black → white edge 의 X (매 보장 시 concurrent OK).
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 매 Modern 변형
|
||||
- 매 Generational: 매 young/old, 매 minor/major GC.
|
||||
- 매 Concurrent: 매 mark 를 매 mutator 와 병행.
|
||||
- 매 Incremental: 매 small chunk 씩 매 stop.
|
||||
- 매 Region-based (G1): 매 heap 을 region 으로 split.
|
||||
|
||||
---
|
||||
## 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Naive mark
|
||||
```c
|
||||
typedef struct Obj {
|
||||
uint8_t marked;
|
||||
size_t n_refs;
|
||||
struct Obj** refs;
|
||||
} Obj;
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
void mark(Obj* o) {
|
||||
if (!o || o->marked) return;
|
||||
o->marked = 1;
|
||||
for (size_t i = 0; i < o->n_refs; i++) mark(o->refs[i]);
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Sweep over heap
|
||||
```c
|
||||
typedef struct Heap { Obj* objects[MAX]; size_t n; Obj* free_list; } Heap;
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
void sweep(Heap* h) {
|
||||
Obj* fl = NULL;
|
||||
for (size_t i = 0; i < h->n; i++) {
|
||||
Obj* o = h->objects[i];
|
||||
if (!o) continue;
|
||||
if (o->marked) {
|
||||
o->marked = 0; // 매 reset for next cycle
|
||||
} else {
|
||||
// 매 free
|
||||
o->refs[0] = (Obj*)fl; // 매 link to free list
|
||||
fl = o;
|
||||
h->objects[i] = NULL;
|
||||
}
|
||||
}
|
||||
h->free_list = fl;
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Tri-color (worklist)
|
||||
```c
|
||||
void mark_tricolor(Obj* roots[], size_t n) {
|
||||
Queue grey;
|
||||
for (size_t i = 0; i < n; i++) { roots[i]->color = GREY; enqueue(&grey, roots[i]); }
|
||||
while (!empty(&grey)) {
|
||||
Obj* o = dequeue(&grey);
|
||||
for (size_t i = 0; i < o->n_refs; i++) {
|
||||
Obj* c = o->refs[i];
|
||||
if (c && c->color == WHITE) { c->color = GREY; enqueue(&grey, c); }
|
||||
}
|
||||
o->color = BLACK;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Write barrier (concurrent invariant)
|
||||
```c
|
||||
// 매 Dijkstra-style: 매 black 이 white 를 가리키지 않도록
|
||||
void write_barrier(Obj* parent, size_t i, Obj* child) {
|
||||
if (parent->color == BLACK && child && child->color == WHITE) {
|
||||
child->color = GREY;
|
||||
enqueue(&grey, child);
|
||||
}
|
||||
parent->refs[i] = child;
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Generational hook (write barrier on old → young)
|
||||
```c
|
||||
// 매 remembered set 에 매 old object 추가
|
||||
void gen_write_barrier(Obj* parent, size_t i, Obj* child) {
|
||||
parent->refs[i] = child;
|
||||
if (parent->gen == OLD && child && child->gen == YOUNG)
|
||||
remembered_set_add(parent);
|
||||
}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### JVM tuning (G1)
|
||||
```bash
|
||||
java -XX:+UseG1GC \
|
||||
-XX:MaxGCPauseMillis=100 \
|
||||
-XX:G1HeapRegionSize=16m \
|
||||
-Xms4g -Xmx4g \
|
||||
-Xlog:gc*:file=gc.log \
|
||||
-jar app.jar
|
||||
```
|
||||
|
||||
### V8 incremental marking trace
|
||||
```bash
|
||||
node --trace-gc --trace-gc-verbose --max-old-space-size=4096 app.js
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | GC |
|
||||
|---|---|
|
||||
| 매 simple, 매 single-thread | Mark-Sweep |
|
||||
| 매 fragmentation 의 우려 | Mark-Compact |
|
||||
| 매 short-lived dominant | Generational + copying young |
|
||||
| 매 latency-critical (<10ms) | ZGC / Shenandoah |
|
||||
| 매 throughput-critical | Parallel/Throughput GC |
|
||||
| 매 ref-cycle 매 잦음 | Tracing GC (RC X) |
|
||||
|
||||
**기본값**: 매 JVM 8GB 초과 = 매 G1 (default), 매 latency 절실 = 매 ZGC.
|
||||
|
||||
## Graph
|
||||
- 부모: [[Garbage Collection]] · [[Memory Management]]
|
||||
- 변형: [[Mark-Compact]] · [[Generational GC]] · [[Concurrent GC]] · [[ZGC]] · [[Shenandoah]]
|
||||
- 응용: [[JVM]] · [[V8]] · [[Go runtime]] · [[CRuby]]
|
||||
- Adjacent: [[Tri-color Marking]] · [[Write Barrier]] · [[Reference Counting]]
|
||||
|
||||
## LLM 활용
|
||||
**언제**: 매 GC 알고리즘 설명, 매 JVM/V8 tuning, 매 GC log 분석, 매 toy GC 작성.
|
||||
**언제 X**: 매 production 의 직접 GC patch (매 risk ↑) — 매 review 만.
|
||||
|
||||
## 안티패턴
|
||||
- **매 Frequent full GC trigger**: 매 -Xmx 부족 / 매 leak.
|
||||
- **매 No write barrier in concurrent**: 매 missed object 의 free.
|
||||
- **매 Recursive mark on deep graph**: 매 stack overflow — 매 worklist 사용.
|
||||
- **매 Tuning without log**: 매 -Xlog:gc* / -verbose:gc 매 필수.
|
||||
- **매 Force System.gc()**: 매 hint, 매 흔히 매 worse latency.
|
||||
|
||||
## 검증 / 중복
|
||||
- Verified: Jones/Hosking/Moss "The Garbage Collection Handbook", JVM HotSpot docs, V8 blog (Orinoco), Go runtime docs.
|
||||
- 신뢰도 A.
|
||||
|
||||
## Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — mark-sweep tri-color/write barrier/tuning 작성 |
|
||||
|
||||
Reference in New Issue
Block a user