[Read Effective Java] Chapter 2 Item 6 "Remove obsolete object references"

Get rid of obsolete object references

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.

Sample code

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;
}

Three Causes of Memory Leaks

First, obsolete reference

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.

Second cache

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

Third listener and callback

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.

Continue

[Read Effective Java] Chapter 2 Item 7 "Avoid Finalizers" https://qiita.com/Natsukii/items/785ae41361cb7324e45b

Recommended Posts

[Read Effective Java] Chapter 2 Item 6 "Remove obsolete object references"
[Effective Java] Remove obsolete object references
[Read Effective Java] Chapter 2 Item 7 "Avoid Finalizers"
[Read Effective Java] Chapter 3 Item 10 "Always Override toString"
[Read Effective Java] Chapter 3 Item 12 "Considering Implementation of Comparable"
Effective Java Chapter 2
[Read Effective Java] Chapter 2 Item 4 "Force uninstantiation with a private constructor"
Effective Java Chapter 6 34-35
[Read Effective Java] Chapter 3 Item 9 "When overriding equals, always override hashCode"
Effective Java Chapter 4 15-22
[Read Effective Java] Chapter 2 Item 5 "Avoid the creation of unnecessary objects"
Effective Java Chapter 3
[Read Effective Java] Chapter 2 Item 1 "Consider static factory methods instead of constructors"
[Read Effective Java] Chapter 3 Item 8 "When overriding equals, follow the general contract"
Effective Java 3rd Edition Chapter 2 Object Creation and Disappearance
[Read Effective Java] Chapter 2 Item 3 "Force singleton characteristics with private constructor or enum type"
Effective Java 3rd Edition Chapter 5 Generics
Effective Java 3rd Edition Chapter 8 Methods
[Read Effective Java] Chapter 2 Item 2 "Consider a builder when faced with a large number of constructor parameters"
Effective Java 3rd Edition Chapter 9 Program General
Java (remove)
Effective Java 3rd Edition Chapter 6 enums and annotations
Effective Java 3rd Edition Chapter 4 Classes and Interfaces
Effective Java 3rd Edition Chapter 7 Lambda and Streams