"매 reachable 만 살리고 — 매 나머지는 sweep.". Mark-Sweep 은 매 1960년 McCarthy 가 Lisp 위해 발명한 매 tracing GC algorithm. 매 root 부터 reachable object 를 mark 하고 매 unmarked 를 sweep. 매 reference counting 의 cycle 문제 해결 — 매 modern GC (V8, JVM, CPython generational) 의 base.
매 핵심
매 2-phase
Mark: 매 GC root (stack, globals, registers) 부터 매 graph traverse, 매 reachable 에 mark bit 1.
Sweep: 매 heap 전체 scan, 매 unmarked object 를 free list 에 추가.
매 GC root
매 stack 의 local variable.
매 global / static variable.
매 CPU register.
매 JNI / native handle.
매 변형
Mark-Compact: sweep 대신 매 살아있는 object 를 압축 → 매 fragmentation 해결.
Tri-color: white / grey / black — 매 incremental / concurrent 가능.
Generational: young (Eden + Survivor) / old — 매 most objects die young 가설.
매 stop-the-world (STW)
매 mark phase 동안 매 mutator (app thread) 정지 — 매 reference graph 일관성.
매 concurrent / incremental GC 는 매 write barrier 로 STW 최소화.
💻 패턴
Pseudocode mark
defmark(obj):ifobjisNoneorobj.marked:returnobj.marked=Trueforrefinobj.references:mark(ref)defgc():# 1. Markforrootinget_roots():mark(root)# 2. Sweepforobjinheap:ifobj.marked:obj.marked=False# reset for next cycleelse:free(obj)
Tri-color iterative mark
WHITE,GREY,BLACK=0,1,2defmark_iterative():# Initially all WHITE except roots → GREYgrey=list(get_roots())forringrey:r.color=GREYwhilegrey:obj=grey.pop()forrefinobj.references:ifref.color==WHITE:ref.color=GREYgrey.append(ref)obj.color=BLACK# Sweep: WHITE → free, BLACK → reset to WHITEforobjinheap:ifobj.color==WHITE:free(obj)else:obj.color=WHITE
// When mutator writes a pointer, GC must know
// (so concurrent mark doesn't miss new references)
voidwrite_field(Object*obj,intidx,Object*val){if(gc_is_marking&&obj->color==BLACK&&val->color==WHITE){val->color=GREY;grey_queue_push(val);}obj->fields[idx]=val;}
매 결정 기준
상황
GC choice
Throughput 중요, latency 무관
Parallel GC (JVM)
균형 (default)
G1GC (JVM), V8 default
매 sub-ms pause
ZGC (JVM 21+), Shenandoah
Embedded / RT
Manual / arena allocator
Functional language
Generational copying (OCaml, Erlang per-process)
기본값: 매 generational + concurrent mark-sweep (G1, V8 Orinoco) — 매 modern runtime 의 standard.