Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Noncompliant Code Example

Wiki Markup
TheThis noncompliant code fragment demonstratedexample below (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 reduces the efficiency of the garbage collector.

Code Block
bgColor#FFCCCC
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; }
}

...

This compliant solution highlights a custom container called ImmutableHolder. When value is assigned in ImmutableHolder's constructor during object creation, it is a younger object member field (of type Hashtable<Integer, String>) that is referencing an older one object (of type Hashtable<Integer, String> ht). This is a much better position to be in as far as the garbage collector is concerned. Note that a shallow copy is used in this case to preserve references to the older value.

Code Block
bgColor#ccccff
public class MutableHolderImmutableHolder {
  private final Hashtable<Integer, String> value;
  // create defensive copy of inputs
  public Object getValue() { return value.clone(); }
  // create defensive copy while returning
  public void setValueImmutableHolder(Hashtable<Integer, String> ht) { value = (Hashtable<Integer, String>)ht.clone(); }
}

...