Wednesday, June 27, 2007

Chapter 7 - Garbage Collection

Chapter 7: Garbage Collection

Objectives

This chapter helps you to prepare for the exam by covering the following objectives:

Know what garbage collection is and how it is performed.

.
You must know what garbage collection is and how it is performed to be able to think
through exam questions related to this topic.
Know when an object is subject to garbage collection. State the behavior that is guaranteed bythe garbage collection system

and write code that explicitly makes objects eligible for collection.

.
Several exam questions require you to know when an object is no longer being referenced
and can be garbage collected. You'll be required to examine examples of program code and
identify specific points within the code where an object becomes subject to garbage
collection.
Know under which conditions finalization takes place.

.
Finalization allows objects to perform cleanup operations before they are discarded.
Knowledge of how finalization takes place is required to evaluate the behavior of code
segments that appear in some exam questions.
Study Strategies

As you read through this chapter, you should concentrate on the following key items:

.
How the garbage collector works
.
When is an object subject to garbage collection
- 114



.
How is an object garbage collected
.
What finalization is used for
.
How finalization works
Chapter Introduction

This chapter addresses a very specific topic—garbage collection—and is very short. However, the
concepts described in this chapter are important. You're very likely to see questions that require a solid
understanding of garbage collection. This chapter provides you with the background you need to
understand the Java garbage-collection mechanism. The review questions and exam questions at the
end of this chapter will test your understanding and will give you an idea of the types of questions that
you may see on the exam. The concepts presented in this chapter are easy to pick up. With a little
study, you should be able to correctly answer all garbage-collection-related questions on the
certification exam.

What Is Garbage Collection?

During the course of a Java program's (or applet's) execution, the program may create and use many
different objects. Each object takes up some amount of valuable memory space and possibly other
resources, such as windows or communication buffers. While the memory and other resources taken up
by each individual object may be neglible, when viewed collectively, the resource drain may be
significant. A program may become unable to perform its processing because it needs memory and
operating system resources which are no longer available.

Garbage collection helps to solve this resource drain. It consists of the following activities:

.
Monitoring the objects used by a program and determining when they are no longer needed.
.
Informing selected objects that they are no longer in use and that they should release any
nonmemory resources.
.
Destroying objects that are no longer in use and reclaiming their resources.
Note
Applets and Garbage Collection Although this chapter's discussion is oriented
toward Java programs, it applies equally as well to Java applets. Just think of
applets as special types of Java programs.

Figure 7.1 summarizes the garbage-collection process. The following section describes how garbage

collection is supported by Java.
Figure 7.1: The garbage-collection process.

How Does the Garbage Collector Work?

The Java garbage collector helps to recycle memory and other resources when they are no longer
needed. It consists of a separate thread of execution that executes in the background and keeps track
of all the objects that are used in a Java program. When an object is no longer needed, it becomes
subject to garbage collection.
At this point, you are probably wondering what it means for an object to be no longer needed and how
the garbage collector determines which objects are needed and which are not. An object is no longer
needed by a program if it is no longer in use and cannot be brought back into use. The garbage
collector determines that an object cannot be used if it is no longer reachable by the program. A

- 115



reachable object is an object that can be accessed directly or indirectly through the variables that are
currently available to the program.
The garbage collector keeps track of the objects that are created and used during a program's
execution. It identifies all objects that can be accessed by the program and those that cannot. An object
becomes unreachable and subject to garbage collection when it is no longer accessible to the program.
I'll give you a concrete example of how this occurs and then come back to the general discussion.
Listing 7.1 shows the code for the GarbageDemo program. This program is designed to quickly use up
all of your memory resources by creating increasingly longer arrays of increasingly longer Stringobjects. The program takes

an integer command-line argument which you can use to specify the
amount of resources it uses. I set the default to 15, which allows the program to execute to completion
when I run it under Windows 98 on a notebook with 96 megabytes of RAM. If your computer has less
RAM, you may need to run the program with a value less than 15. Start at 14 and work backwards until
your program is able to execute without running out of memory.

When I run the program on my computer, it displays the following output:
1 is being collected.
2 is being collected.
3 is being collected.
4 is being collected.
5 is being collected.
6 is being collected.
7 is being collected.
8 is being collected.
9 is being collected.
10 is being collected.
11 is being collected.
12 is being collected.


This output is displayed by the finalize() method of each Garbage object, indicating that the
garbage collector has determined that the object has become unreachable. (The finalize() method
is invoked on an object by the garbage collector so that the object may perform cleanup before it is
reclaimed by the garbage collector.
)
The above output indicates that 12 Garbage objects were being finalized by the garbage collector.
These objects had become unreachable because they no longer were referenced by the g field variable
of the GarbageDemo class. To understand how this happened, let's look at the run() method:


void run() {
for(int i=1;ig = new Garbage(i);
}
}
With each iteration of the for statement, a new Garbage object is created and assigned to the gvariable. When a new object is

assigned to the g variable, the previous object that was referenced by
the g variable is no longer accessible by g or any other variable or object. Hence, that object becomes
subject to garbage collection.

Listing 7.1: GarbageDemo.java—An Example of Garbage Collection in Action
public class GarbageDemo {
Garbage g;
int max;
public static void main(String[] args) {

- 116



int n = 15;
if(args.length > 0) n = (new Integer(args[0])).intValue()
;
GarbageDemo app = new GarbageDemo(n)
;
app.run()
;


}
public GarbageDemo(int n)
{


max = n;
}
void run()
{


for(int i=1;i{
g = new Garbage(i)
;
}


}
}
class Garbage {

String[] trash;
int value;
public Garbage(int n)
{


value = n;
trash = new String[n]
;
trash[0] = "This String uses up memory resources. "
;
for(int i=1;i

trash[i] = trash[i-1] + trash[i-1];
}
protected void finalize() {

System.out.println(value+" is being collected.");
}

}
Having seen an example of garbage collection in action, let's take a look at how it works. Figure 7.2
summarizes the operation of the garbage collector. The garbage collector keeps track of all variables
that are accessible to the program. These variables reference objects, which in turn may reference

- 117



other objects, and so on. These are the set of reachable objects. An object becomes unreachable when
it is no longer referenced by the program variables or reachable objects. When this happens it is subject
to garbage collection.


Figure 7.2: How the garbage collector works.

When Is an Object Subject to Garbage Collection?

When an object becomes subject to garbage collection, it is not necessarily garbage collected
immediately. It may, in fact, never be garbage collected. The program may terminate before the
garbage collector gets around to reclaiming the object. Being subject to garbage collection simply
means that an object is eligible to be reclaimed.
In the previous section, I displayed the results of running GarbageDemo on my computer. Note that only
12 objects had their finalize() method invoked by the garbage collector. What happened to
Garbage(13) and Garbage(14)? Garbage(13) was subject to garbage collection, but the garbage
collector never got around to invoking its finalize() method. Garbage(14) remained reachable
until the program's termination.

The important point to remember about garbage collection is that an object becomes subject to garbage
collection when it is no longer accessible. If and when the object is collected is subject to the garbage
collector. Because the garbage collector runs asynchronously to your program (as a separate thread),
there is no telling when it will execute, which unreachable objects it will reclaim, and when it will reclaim
those objects.

Where in a program's execution does an object become subject to garbage collection? This occurs
when the object becomes unreachable. If you are asked a multiple-choice, garbage-collection–related
question that has an answer choice specifically stating when an object is actually collected, reject that
answer. Garbage collection is non-determinable. There is no way of telling if and when an object will be
collected.

How Is Finalization Performed?

The example of Listing 7.1 makes use of the finalize() method of the Garbage objects to indicate
for which objects the garbage collector has initiated the garbage-collection process. An object's
finalize() method is invoked by the garbage collector when it determines that the object has
become unreachable.
The finalize() method is defined in the Object class. However, the Object implementation of
finalize() performs no action. Classes override finalize() to perform cleanup prior to garbage
collection. For example, a networking object may close down a TCP connection prior to garbage
collection.
If an object becomes unreachable, there is no guarantee that the object's finalize() method will be
invoked. However, if an object does have a finalize() method, this method will be invoked before
the object is garbage collected. Figure 7.3 illustrates this fine point.

- 118



Figure 7.3: Reachability, finalization, and garbage collection.
When an object's finalize() method is invoked, the object may perform an action that will make the
object reachable again. For example, the object may invoke a method that results in its being included
in a Vector of reachable objects.
Note Finalization An object may invoke the finalize() method of its superclass to
perform any required final-ization.
After the finalize() method has completed its processing and returned to the garbage collector, the
garbage collector performs no reclamation processing until the garbage collector has again identified
the object as being unreachable and subject to collection. At this point, the object is discarded, and its
memory resources are reclaimed. Note that the finalize() method is never invoked more than once
for a given object.

Chapter Summary

This chapter described the operation of the garbage collector and covered the circumstances in which
an object is subject to garbage collection. It explained the difference between being subject to garbage
collection and having garbage collection actually performed. This chapter also covered finalization and
explained how finalization fits into the garbage-collection process. You should now be prepared to test
your knowledge of these subjects. The following review questions and exam questions will let you know
how well you understand this material and will give you an idea of how you'll do in garbage-collection–
specific exam questions. They'll also indicate which material you need to study further.

Key Terms

.
Garbage collection
.
Reachable
.
Unreachable
.
Finalization
Review Questions

1.
What is the purpose of garbage collection?
2.
When is an object subject to garbage collection?
3.
How many times may an object's finalize() method be invoked?
4.
Can an unreachable object become reachable again?
5.
Under what conditions is an object's finalize() method invoked by the garbage
collector?
6.
What is the purpose of finalization?
7. Does garbage collection guarantee that a program will not run out of memory?
8.
If an object is garbage collected, can it become reachable again?
9.
Can an object be garbage collected while it is still reachable?
10. Can an object's finalize() method be invoked while it is reachable?
- 119



Exam Questions

1.
At which line in the following code is the Vector object created in line 4 first subject to
garbage collection?
2. 1. import java.util.*;
3. 2. public class Question {
4. 3. public static void main(String[] args) {
5. 4. Vector v1 = new Vector(); a
6. 5. Vector v2 = new Vector();
7. 6. v1.add("This");
8. 7. v1.add(v2);
9. 8. String s = (String) v1.elementAt(0);
10. 9. v1 = v2;
11. 10. v2 = v1;
12. 11. v1.add(s);
13. 12.
}
13.
}
A.
Line 5
B.
Line 6
C.
Line 8
D.
Line 9
14. At which line in the following code is the Vector object, created in line 4, first subject to
garbage collection?
15. 1. import java.util.*;
16. 2. public class Question {
17. 3. public static void main(String[] args) {
18. 4. Vector v1 = new Vector();
19. 5. Vector v2 = new Vector();
20. 6. v1 = null;
21. 7. Vector v3 = v1;
22. 8. v1 = v2;
23. 9. v1.add("This");
24. 10. v1.add(v2);
25. 11. String s = (String) v1.elementAt(0);
26. 12. v1 = v2;
27. 13. v2 = v1;
28. 14. v1.add(s);
29. 15.
}
16.
}
A.
Line 6
B.
Line 7
C.
Line 8
D.
Line 12
30. How can you force an object to be garbage collected?
A.
Invoke its finalize() method.
B.
Remove all references to the object.
C.
Use all memory that is available to the program.
D.
You cannot force an object to be garbage collected.
31. If an object with a finalize() method has been garbage collected, which of the
following are true about that object?
A.
The object became unreachable.
B. The object's finalize() method was invoked by the garbage collector.
C.
The memory used by the object is subject to reuse.
- 120



D.
The object did not implement any interfaces.
32. Which of the following are true about an unreachable object?
A.
It will be garbage collected.
B. Its finalize() method will be invoked.
C.
It can become reachable again.
D.
It has a null value.
33. Which of the following are true about the Java garbage collector as implemented by the
Java 2 Platform?
A.
It guarantees that Java programs will never run out of memory.
B.
It executes as a low-priority, background thread.
C.
It keeps track of which objects are reachable and unreachable.
D.
It can be directed to garbage collect specific objects.
34. Which of the following are true about an object's finalize() method?
A.
It can be invoked multiple times by the garbage collector.
B.
If it is invoked, the object will be garbage collected.
C.
If the object has been garbage collected, its finalize() method has
been invoked.
D.
It must perform cleanup operations.
Answers to Review Questions

1.
The purpose of garbage collection is to identify and discard objects that are no longer
needed by a program so that their resources may be reclaimed and reused.
2.
An object is subject to garbage collection when it becomes unreachable to the program
in which it is used.
3.
An object's finalize() method may only be invoked once.
4.
An unreachable object may become reachable again. This can happen when the
object's finalize() method is invoked and the object performs an operation which
causes it to become accessible to reachable objects.
5.
The garbage collector invokes an object's finalize() method when it detects that the
object has become unreachable.
6.
The purpose of finalization is to give an unreachable object the opportunity to perform
any cleanup processing before the object is garbage collected.
7.
Garbage collection does not guarantee that a program will not run out of memory. It is
possible for programs to use up memory resources faster than they are garbage
collected. It is also possible for programs to create objects that are not subject to
garbage collection. Try running the GarbageDemo program of Listing 7.1 with a
command-line argument of 100.
8.
Once an object is garbage collected, it ceases to exist. It can no longer become
reachable again.
9.
A reachable object cannot be garbage collected. Only unreachable objects may be
garbage collected.
10. An object's finalize() method cannot be invoked by the garbage collector while the
object is still reachable. However, an object's finalize() method may be invoked by
other objects.
Answers to Exam Questions

1.
D. The object created in line 4 is assigned to the v1 variable up to line 9. At this point, a
new object is assigned to the v1 variable, and the object created in line 4 is no longer
accessible to the program.
2.
A. In line 6, the null value is assigned to the v1 variable. This causes the object
created in line 4 to become unreachable.
3.
D. The garbage collector operates in a non-determined manner. It cannot be forced to
garbage collect a specific object.
4.
A, B, and C. Only unreachable objects are garbage collected. If an object has a
finalize() method, the garbage collector will invoke the object's finalize()
- 121


method before garbage collecting the object. After an object has become garbage
collected, its memory is subject to reuse.

5.
C. There's no guarantee that an unreachable object will be garbage collected or that its
finalize() method will be invoked. However, an unreachable object can become
reachable again. This can happen if the object makes itself accessible to other
reachable objects when its finalize() method is invoked. There is no restriction that
requires an unreachable object to have a null value.
6.
B and C. The garbage collector cannot prevent a program from running out of memory.
It does, however, execute as a low-priority background thread and keep track of which
objects are reachable and unreachable. It cannot be directed to garbage collect an
object.
7.
C. An object's finalize() method may only be invoked once by the garbage collector.
If an object's finalize() method is invoked, there is no guarantee that it will be
garbage collected. However, if the object has been garbage collected, then its
finalize() method must have been invoked. The purpose of the finalize()
method is to perform cleanup operations prior to garbage collection. However, it is not
required to do so.

No comments: