Garbage Collection
Garbage Collection
A memory management technique that automatically frees memory that is no longer in use. Used in Java, Python, Go, and others.
Garbage Collection
A memory management technique that automatically frees memory that is no longer in use. Used in Java, Python, Go, and others.
Garbage collection (GC) is a memory management technique that automatically finds and frees the parts of dynamically allocated memory that a program no longer uses. Unlike languages with manual memory management such as C/C++, languages like Java, Python, Go, and JavaScript use GC to prevent memory leaks and dangling pointer problems.
The basic principle of GC is "reachability." Objects that can be reached by following reference chains from the roots (global variables, stack, registers) are considered alive, while unreachable objects are judged to be garbage and collected.
Representative GC algorithms include Mark-and-Sweep (marking and removing unreachable objects), Reference Counting (removing an object when its reference count reaches 0), and Generational GC (managing objects by dividing them into generations). Java's G1GC and ZGC and Go's Concurrent GC are designed to minimize application pause time.
GC is convenient, but the "Stop-the-World" phenomenon can cause temporary performance degradation. Therefore, real-time systems and applications where low latency matters use techniques such as GC tuning and memory pooling alongside it.
// 가비지 컬렉션의 동작 원리 이해
// 1. 객체가 생성되어 메모리에 할당됨
let user = {
name: "김개발",
data: new Array(1000000).fill("데이터")
};
// 2. user 변수가 객체를 참조하고 있어 GC 대상이 아님
console.log(user.name); // "김개발"
// 3. 참조를 제거하면 GC 대상이 됨
user = null; // 이제 원래 객체에 접근할 방법이 없음
// 4. GC가 동작하면 해당 메모리가 해제됨
// (정확한 시점은 런타임이 결정)
// WeakMap/WeakSet - 약한 참조로 GC 허용
const cache = new WeakMap();
let obj = { id: 1 };
cache.set(obj, "캐시된 값");
obj = null; // obj에 대한 강한 참조가 없어지면
// WeakMap의 항목도 GC 대상이 됨
// 순환 참조 - 현대 GC는 처리 가능
function createCircular() {
const a = {};
const b = {};
a.ref = b;
b.ref = a;
// 함수 종료 후 a, b 모두 도달 불가능 → GC 대상
}
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free