Closed okhee closed 2 years ago
=> GC만 믿고 메모리 관리에 신경쓰지 않는다면 메모리 누수가 발생할 수 있다!
m.put (key, new WeakReference (value))
https://github.com/jbloch/effective-java-3e-source-code
메모리 누수의 주범
=> 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 란?
m.put (key, new WeakReference (value))
참고