Closed gmelon closed 1 year ago
MyClass obj = new MyClass(); // obj가 new MyClass() 를 들고 있으므로 GC X
obj = null; // 이 시점부터 new MyClass() 인스턴스가 gc의 대상이 됨
SoftReference<MyClass> obj = new SoftReference<>(new MyClass());
// 메모리가 부족하면 new MyClass() 인스턴스는 GC의 대상
WeakReference<MyClass> obj = new WeakReference<>(new MyClass());
// 메모리에 관계 없이 new MyClass() 인스턴스는 항상 GC의 대상
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