Garbage Collection
Garbage Collection
Automatically frees unused memory. Supported in Java, Python, and Go.
Garbage Collection
Automatically frees unused memory. Supported in Java, Python, and Go.
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.
// 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