Java Reference
In-Depth Information
determining when an object is eligible for garbage collection. Consider the following class
named Dog that contains a finalize method that prints out a simple message:
1. public class Dog {
2. private String name;
3. private int age;
4.
5. public Dog(String name, int age) {
6. this.name = name;
7. this.age = age;
8. }
9.
10. public void finalize() {
11. System.out.println(name + “ is being garbage collected”);
12. }
13. }
The following program instantiates two Dog objects and stores them in a java.util
.Vector . Examine this program and see if you can determine when the two Dog objects
become eligible for garbage collection:
1. import java.util.Vector;
2. public class GCDemo3 {
3. public static void main(String [] args) {
4. Vector<Dog> vector = new Vector<Dog>();
5. Dog one = new Dog(“Snoopy”, 10);
6. Dog two = new Dog(“Lassie”, 12);
7.
8. vector.add(one);
9. vector.add(two);
10.
11. one = null;
12. System.out.println(“Calling gc once...”);
13. System.gc();
14.
15. vector = null;
16. System.out.println(“Calling gc twice...”);
17. System.gc();
18.
19. two = null;
20. System.out.println(“Calling gc again...”);
Search WWH ::




Custom Search