Garbage collectors may look like magic to a language that manages memory manually, such as C. However, there are still causes for memory leaks, so be careful.
Example 1
//"Memory leak"Can you find it?
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
this.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];
}
/**
*Approximately double the procedure each time you need to increase the array
*Secure at least the capacity of another element.
*/
private void ensureCapacity() {
if (elements.length == size)
elements = Array.copyOf(elements, 2 * size + 1);
}
}
Example 2
public Object pop() {
if (size==0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; //Get rid of obsolete references
return result;
}
Example 1 looks fine at first glance, but holds an obsolete reference. You can prevent memory leaks by setting null for references that you no longer need as in Example 2.
However, you don't have to set excessive nulls for all used programs. The Stack class has its own memory management. The garbage collector does not know which references in such classes are unnecessary. You can effectively tell the garbage collector what is invalid by manually setting null.
Once you've cached an object reference, it's easy to forget that it's there, and it's easy to leave it in the cache long after the object reference is meaningless. If you want to implement a cache that makes sense for that entry as long as there is a reference to the key of the entry outside the cache, then it's a good idea to represent that cache in WeakHashMap. WeakHashMap: Automatically removed when entries are obsolete
If you implement an API that does not explicitly unregister, callbacks will be accumulated unless some processing is performed. The best way to ensure that callbacks are garbage collected quickly is to store only weak references to them.
[Read Effective Java] Chapter 2 Item 7 "Avoid Finalizers" https://qiita.com/Natsukii/items/785ae41361cb7324e45b
Recommended Posts