💻 Programming

Garbage Collection

Garbage Collection

Automatically frees unused memory. Supported in Java, Python, and Go.

📖 Detailed Explanation

Garbage Collection (GC) is a memory management technique that automatically identifies and frees memory that a program no longer uses. It was first devised in 1959 by John McCarthy for the Lisp language, and today it is adopted as a core feature in most modern programming languages, including Java, Python, Go, and JavaScript.

The most representative GC algorithm is Mark-and-Sweep. This algorithm first starts from the roots (global variables, stack variables, etc.), 'marks' all reachable objects, and then removes the unmarked objects from memory (Sweep). Reference Counting is a method that tracks the number of times each object is referenced and frees it immediately when the reference count reaches 0.

Modern GC introduced the concept of Generational Collection to improve efficiency. Based on the 'weak generational hypothesis' that most objects disappear quickly after creation, it collects the Young Generation frequently and the Old Generation less often. Java's G1 GC and ZGC, and Go's Concurrent GC, among others, make use of this principle.

In practice, GC greatly reduces the memory management burden on developers, but GC pauses (Stop-the-World) can affect performance. In particular, GC tuning is essential in real-time systems and applications where low latency is important, and the latest GCs focus on reducing pause times to the millisecond range.

💻 Code Example

// Java - GC 동작 이해와 메모리 관리

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class GarbageCollectionDemo {

    public static void main(String[] args) {
        // 1. 기본적인 GC 대상 생성
        createGarbageObjects();

        // 2. WeakReference 활용 예시
        demonstrateWeakReference();

        // 3. 명시적 GC 요청 (권장하지 않음)
        System.gc();  // JVM에 GC 요청 (실행 보장 없음)

        // 4. 메모리 상태 확인
        printMemoryStatus();
    }

    static void createGarbageObjects() {
        // 이 메서드가 끝나면 list는 GC 대상이 됨
        List list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            list.add(new byte[1024 * 1024]); // 1MB 객체
        }
        System.out.println("100MB 객체 생성 완료");
        // 메서드 종료 시 list 참조 소멸 -> GC 대상
    }

    static void demonstrateWeakReference() {
        // Strong Reference: GC 대상 아님
        Object strongRef = new Object();

        // Weak Reference: 메모리 부족 시 GC 대상
        WeakReference weakRef = new WeakReference<>(new Object());

        System.out.println("GC 전 WeakRef: " + weakRef.get());
        System.gc();
        System.out.println("GC 후 WeakRef: " + weakRef.get()); // null 가능
    }

    static void printMemoryStatus() {
        Runtime runtime = Runtime.getRuntime();
        long total = runtime.totalMemory() / 1024 / 1024;
        long free = runtime.freeMemory() / 1024 / 1024;
        long used = total - free;

        System.out.println("=== 메모리 상태 ===");
        System.out.println("전체: " + total + "MB");
        System.out.println("사용: " + used + "MB");
        System.out.println("여유: " + free + "MB");
    }
}

// JVM 실행 옵션으로 GC 로그 확인:
// java -Xlog:gc* -Xmx512m GarbageCollectionDemo
                
            
        

        
        

🗣️ 실무에서 이렇게 말하세요

💬 회의에서
"최근 API 응답 지연이 발생하는데, GC 로그를 확인해보니 Full GC가 너무 자주 발생하고 있어요. 힙 사이즈를 늘리거나 G1 GC에서 ZGC로 전환을 검토해봐야 할 것 같습니다."
💬 면접에서
"Java GC는 Young Generation과 Old Generation으로 나뉘어 동작합니다. 새로운 객체는 Eden 영역에 할당되고, Minor GC를 거쳐 Survivor 영역을 거쳐 Old Generation으로 승격됩니다. Stop-the-World 시간을 최소화하기 위해 G1 GC는 Region 단위로 병렬 수집을 수행합니다."
💬 코드 리뷰에서
"이 부분에서 매 요청마다 큰 객체를 새로 생성하고 있네요. 객체 풀링을 적용하거나 재사용 가능한 버퍼를 사용하면 GC 압력을 줄일 수 있습니다. 특히 Young GC 빈도가 높아 보여요."

이 주제로 모의면접 보기 → WIA SOOM AI 면접 · 무료로 시작

⚠️ 흔한 실수 & 주의사항

❌
System.gc() 남용하지 않기

명시적 GC 호출은 JVM에 '힌트'일 뿐 실행을 보장하지 않습니다. 오히려 불필요한 Full GC를 유발하여 성능을 저하시킬 수 있으므로, 프로덕션 코드에서는 사용을 피하세요.

❌
메모리 누수(Memory Leak) 주의

GC가 있어도 메모리 누수는 발생합니다. static 컬렉션에 객체를 계속 추가하거나, 이벤트 리스너를 해제하지 않으면 객체가 참조로 연결되어 GC 대상에서 제외됩니다.

✅
GC 로그 분석 습관화

-Xlog:gc* 옵션으로 GC 로그를 활성화하고, GCViewer나 GCEasy 같은 도구로 분석하세요. GC 빈도, 일시 정지 시간, 힙 사용 패턴을 파악하면 튜닝 포인트를 찾을 수 있습니다.

🔗 관련 용어

📚 더 배우기