...
Wiki Markup |
---|
This noncompliant code example (based on \[[Goetz 04|AA. Java References#Goetz 04]\]) shows a container, {{MutableHolder}}. In {{MutableHolder}}, the instance field {{value}} can be updated to reference a new value using the {{setValue()}} method which makes its existence long-term. This reducesslows the efficiency of the down garbage collectorcollection. |
Code Block | ||
---|---|---|
| ||
public class MutableHolder { private Hashtable<Integer, String> value; // not final public Object getValue() { return value; } public void setValue(Hashtable<Integer, String> ht) { value = (Hashtable<Integer, String>)ht; } } |
...
Array based data structures such as ArrayLists
are an exception as the programmer has to explicitly set only a few of the array elements to null
to indicate their demise.
Long-lived objects containing short-lived objects
Always remove short-lived objects from the long-lived container objects when the task is over. For example, objects attached to a java.nio.channels.SelectionKey
object must be removed when they are no longer needed. Doing so reduces the possibility of memory leaks.
Do Not Explicitly Invoke the Garbage Collector
...