NMP-Study / EffectiveJava2022

Effective Java Study 2022
5 stars 0 forks source link

아이템 7. 다 쓴 객체 참조를 해제하라 #7

Closed okhee closed 2 years ago

KimYunsang-v commented 2 years ago

메모리 누수의 주범

=> GC만 믿고 메모리 관리에 신경쓰지 않는다면 메모리 누수가 발생할 수 있다!

[1] 다 쓴 참조를 여전히 갖고 있는 경우

JAVA에서도 자기 메모리를 직접 관리하는 클래스라면 메모리 누수에 주의해야 한다!

stack 예제 ```java public class Stack { private Object[] elements; private int size = 0; private static final int DEFAULT_INITIAL_CAPACITY = 16; public Stack() { elements = new Object[DEFAULT_INITIAL_CAPACITY]; } public void push(Object e) { ensureCapacity(); elements[size++] = e; } public Object pop() { if (size == 0) throw new EmptyStackException(); return elements[--size]; } private void ensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } public static void main(String[] args) { Stack stack = new Stack(); for (String arg : args) stack.push(arg); while (true) System.err.println(stack.pop()); } } ```

[2] 캐시

객체 참조를 캐시에 넣고, 해당 객체를 다 쓴 뒤로도 그냥 놔두는 경우

해결책

[3] 리스너 혹은 콜백

클라이언트가 콜백 등록 후 명확히 해지하지 않는다면 콜백은 계속 쌓여감

해결책

WeakHashMap 란?

참고

KimYunsang-v commented 2 years ago

이펙티드 자바 코드 repo

https://github.com/jbloch/effective-java-3e-source-code