💻 Programming

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.

📖 Detailed Explanation

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.

💻 Code Example

JavaScript
// 가비지 컬렉션의 동작 원리 이해

// 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 대상
}

🗣️ Examples of Practical Conversations

Backend developer
"In production, GC pause times sometimes go up to 200ms. It's causing response delays. How can we fix it?"
Senior developer
"Switching from G1GC to ZGC can bring pause times down to under 10ms. However, memory overhead increases slightly."
Backend developer
"Reducing object creation is another way. How about reusing frequently created DTOs with an object pool?"
Interviewer
"Why does Java's Generational GC divide memory into a Young Generation and an Old Generation?"
Candidate
"It's based on the 'weak generational hypothesis' that most objects die quickly after creation. Collecting the Young area frequently is efficient, and objects that survive for a long time are moved to Old to reduce how often they are collected."
Interviewer
"Can memory leaks occur even in a GC environment?"
Candidate
"Yes, they are caused by unintentionally retained references. For example, when you only add objects to a static collection and never remove them, or when a closure unnecessarily captures an outer variable."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer
"This loop creates a new StringBuilder every iteration. If you create it once outside the loop and reuse it, you can reduce the GC load."
Author
"Ah, you're right. I'll change it to just empty the contents with the clear() method and reuse it."
Reviewer
"Also, if you set this HashMap's reference to null after use or narrow its scope, it will become eligible for GC sooner."

⚠️ Cautions

🔗 Related Terms

📚 Learn More