I am trying a new idea here so if the following diagrams look weird - sorry!
Dear Reader,
A fellow Javarancher asked me to explain the answer to the following Garbage Collector question:
Given:
1. class X2 {
2. public X2 x;
3. public static void main(
String [] args) {
4. X2 x2 = new X2();
5. X2 x3 = new X2();
6. x2.x = x3;
7. x3.x = x2;
8. x2 = new X2();
9. x3 = x2;
10. doComplexStuff();
11. }
12. }
After line 9, how many objects are eligible for garbage collection?
I think the best way to tackle such a problem is to draw a picture, so given the limitations of characters here goes:
(By the way boxes are reference varaibles and blobby things are objects)
Lines 4 and 5 create reference variables x2 and x3, and they create two new X2 objects to which x2 and x3 refer:
-----------------
| x2 | - - - - - - - - - - > / \
---- / ------ \
| | x2.x | |
\ ------ /
---------------
(line 4 X2 object)
-----------------
| x3 | - - - - - - - - - - > / \
---- / ------ \
| | x3.x | |
\ ------ /
---------------
(line 5 X2 object)
The Stack The Heap
Figure 1 - After lines 4 and 5 run
Notice that each object has a reference variable inside! Notice also that x2 and x3 live on the stack, and the objects live on the heap!!
Lines 6 and 7 refer the two objects to each other by using the instance variable x.
-----------------
| x2 | - - - - - - - - - - > / \
---- / ------ \
-> | | x2.x |--- |
| \ ------ / \
| --------------- |
| (line 4 X2 object) |
| |
| |
----| ------------- |
| x3 | - - - - - - - - - - > / \ |
---- | / ------ \ <-
--- | -- | x3.x | |
\ ------ /
---------------
(line 5 X2 object)
The Stack The Heap
Figure 2 - After lines 6 and 7 run
Line 8 creates a new object of type X2 and uses the existing reference variable x2 to refer to it. This means the x2 reference to the object created on line 4 is gone.
Line 9 changes x3's reference from the object created on line 5 to the object created on line 8. Now the line 4 and 5 objects exist as an 'island of isolation'. They refer to each other but no one can refer to them. They are now garbage collector bait.
-------------
/ \
/ ------ \
--------> | | x2.x | |
/ ----> \ ------ /
/ / ---------------
/ / (line 8 X2 object)
/ /
/ /
/ /
/ /
/ /
----/ /-------------
| x2 | -- / / \
---- / / ------ \
/ -> | | x2.x |--- |
/ | \ ------ / \
/ | --------------- |
/ | (line 4 X2 object) |
/ | |
/ | |
---- /| ------------- |
| x3 | / \ |
---- | / ------ \ <-
--- | -- | x3.x | |
\ ------ /
---------------
(line 5 X2 object)
The Stack The Heap
Figure 3 - After lines 8 and 9 run
So the answer is, after line 9 runs, two objects are eligible for garbage collection. After line 9 runs there are a total of three objects on the Heap (of course ALL objects are ALWAYS on the Heap). At this point there are five reference variables. Each X2 object has an instance variable that is a reference variable, and x2 and x3 are on the Stack.
Hope that helps!