Java Reference
In-Depth Information
// Kill the element that is now irrelevant
longLivedList.get(someIndex).killMe();
Thegarbagecollectorcannotcollectthedead
DataElement
objectuntilitbecomesun-
referenced. Note that all methods that operate on objects of class
DataElement
must also
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:
class DataElement {
// Dead flag removed
// Other fields
}
// Elsewhere
List<DataElement> longLivedList = new ArrayList<DataElement>();
// Processing that renders an element irrelevant
// Set the reference to the irrelevant DataElement to null
longLivedList.set(someIndex, null);
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 known as the
Sentinel pattern
).
class DataElement {
public static final DataElement NULL = createSentinel();
// Dead flag removed
// Other fields