Java Reference
In-Depth Information
The fact that you don't need to remember to destroy every
object you create is one of the features that makes Java a pleas‐
ant language to work with. It is also one of the features that
makes programs written in Java less prone to bugs than those
written in languages that don't support automatic garbage
Different VM implementations handle garbage collection in different ways, and the
specifications do not impose very stringent restrictions on how GC must be imple‐
mented. Later in this chapter, we will discuss the HotSpot JVM (which is the basis of
both the Oracle and OpenJDK implementations of Java). Although this is not the
only JVM that you may encounter, it is the most common among server-side
deployments, and provides a good example of a modern production JVM.
Memory Leaks in Java
The fact that Java supports garbage collection dramatically reduces the incidence of
memory leaks . A memory leak occurs when memory is allocated and never
reclaimed. At first glance, it might seem that garbage collection prevents all memory
leaks because it reclaims all unused objects.
A memory leak can still occur in Java, however, if a valid (but unused) reference to
an unused object is left hanging around. For example, when a method runs for a
long time (or forever), the local variables in that method can retain object references
much longer than they are actually required. The following code illustrates:
public static void main ( String args []) {
int bigArray [] = new int [ 100000 ];
// Do some computations with bigArray and get a result.
int result = compute ( bigArray );
// We no longer need bigArray. It will get garbage collected when
// there are no more references to it. Because bigArray is a local
// variable, it refers to the array until this method returns. But
// this method doesn't return. So we've got to explicitly get rid
// of the referenceourselves, so the garbage collector knows it can
// reclaim the array.
bigArray = null ;
// Loop forever, handling the user's input
for (;;) handle_input ( result );
Memory leaks can also occur when you use a HashMap or similar data structure to
associate one object with another. Even when neither object is required anymore,
the association remains in the hash table, preventing the objects from being
reclaimed until the hash table itself is reclaimed. If the hash table has a substantially
longer lifetime than the objects it holds, this can cause memory leaks.
Search WWH ::

Custom Search