Versions Compared

Key

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

...

This guideline specifically addresses objects in containers. For an instance where nulling out objects does not aid garbage collection, see OBJ54-JG. Do not attempt to help the garbage collector by setting local reference variables to null.

Noncompliant Code Example (Removing Short-Lived Objects)

In this noncompliant code example, a long-lived ArrayList contains references to both long- and short-lived elements. The programmer marks elements that have become irrelevant by setting a "dead" flag in the object.

...

The garbage collector cannot collect the dead DataElement object until it becomes unreferenced. Note that all methods that operate on objects of class DataElement must check whether the instance in hand is dead.

Compliant Solution (Set Reference to null)

In this compliant solution, rather than use a dead flag, the programmer assigns null to ArrayList elements that have become irrelevant:

...

Note that all code that operates on the longLivedList must now check for list entries that are null. 

Compliant Solution (Use Null Object Pattern)

This compliant solution avoids the problems associated with intentionally null references by using a singleton sentinel object. This technique is known as the Null Object pattern (also as the Sentinel pattern). 

...

When using this pattern, the NULL object must be a singleton and must be final. It may be either public or private, depending on the overall design of the DataElement class. The state of the NULL object should be immutable after creation; immutability can be enforced either by using final fields or by explicit code in the methods of the DataElement class. See Chapter 8, "Behavioral Patterns, the Null Object,"€ of Patterns in Java, Vol. 1, second edition [Grand 2002], for additional information on this design pattern, and also ERR08-J. Do not catch NullPointerException or any of its ancestors.

Applicability

Leaving short-lived objects in long-lived container objects may consume memory that cannot be recovered by the garbage collector, leading to memory exhaustion and possible denial of service attacks.

Bibliography

[Grand 2002]

Chapter 8, "Behavioral Patterns, the Null Object"€

...