2023-java-study / book-study

북 스터디 기록 레포지토리
0 stars 0 forks source link

[Item 7] WeakHashMap의 동작 방식 #20

Closed gmelon closed 1 year ago

gmelon commented 1 year ago
gmelon commented 1 year ago

참조 유형

Strong Reference

MyClass obj = new MyClass(); // obj가 new MyClass() 를 들고 있으므로 GC X

obj = null; // 이 시점부터 new MyClass() 인스턴스가 gc의 대상이 됨

Soft Reference

SoftReference<MyClass> obj = new SoftReference<>(new MyClass());

// 메모리가 부족하면 new MyClass() 인스턴스는 GC의 대상

Weak Reference

WeakReference<MyClass> obj = new WeakReference<>(new MyClass());

// 메모리에 관계 없이 new MyClass() 인스턴스는 항상 GC의 대상

Phantom Reference

WeakHashMap의 동작 방식

WeakHashMap 코드 일부

private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
    V value;
    final int hash;
    Entry<K,V> next;

    Entry(Object key, V value,
          ReferenceQueue<Object> queue,
          int hash, Entry<K,V> next) {
        super(key, queue); // HashMap의 key를 WeakReference의 생성자로 전달한다
        this.value = value;
        this.hash  = hash;
        this.next  = next;
    }

동작 예시

WeakHashMap<MyClass, String> map = new WeakHashMap<>();

MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();

map.put(obj1, "obj1");
map.put(obj2, "obj2");

obj1 = null; // obj1에 대한 참조가 WeakHashMap 내의 WeakReference만 남게 됨 -> gc의 대상이 됨

System.gc(); // 항상 gc를 보장하진 않음, gc가 이뤄졌다고 가정

map.keySet()
    .forEach(key -> System.out.println(map.get(key))); // obj2

참고 자료