Java Reference
In-Depth Information
Applicability
Direct buffers are beyond the scope of Java's garbage collector and can cause memory
leaks if they are used injudiciously. In general, direct buffers should be allocated only
when their use provides a significant gain in performance.
Bibliography
[API 2013]
Class
ByteBuffer
49. Remove short-lived objects from long-lived container objects
Always remove short-lived objects from long-lived container objects when the task is
over.Forexample,objectsattachedtoa
java.nio.channels.SelectionKey
objectmust
be removed when they are no longer needed. Doing so reduces the likelihood of memory
leaks. Similarly, use of array-based data structures such as
ArrayList
can introduce a re-
quirement to indicate the absence of an entry by explicitly setting
ArrayList
's individual
array element to
null
.
This guideline specifically addresses objects referred to from containers. For an ex-
ample where nulling out objects does not aid garbage collection, see
Guideline 75
,
“
Do
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 irrel-
evant by setting a “dead” flag in the object.
class DataElement {
private boolean dead = false;
// Other fields
public boolean isDead() { return dead; }
public void killMe() { dead = true; }
}
// ... Elsewhere
List<DataElement> longLivedList = new ArrayList<DataElement>();
// Processing that renders an element irrelevant