|
In the last sections, we learned that an object becomes unreachable when no references are referring to it. There are also situations where an object could be unreachable (and thus eligible for garbage collection) even when it has some object references pointing towards it. This situation can be best explained with objects that store a reference to another object in its member variable. For instance, in the example we have been discussing so far, assume that the Car class has a reference variable called anotherCar which points to another Car object.
package com.example.automobiles;
class Car {
Car anotherCar;
public Car(){}
public Car(String name){
}
}
If one Car object points to another Car object and it in turn points to the first Car object, they form a cyclic reference. Listing 6.3 first creates three Car objects. Then each Car object is made to point to another Car object with anotherCar reference variable. Thus they form cyclic reference among them. After that all three Car objects are orphaned by nullifying their (root) references.

Figure 6.3 shows memory model when partial code (up to line 9) from listing 6.3 is executed. As you can see the each of the three Car objects have two references pointing towards them, one root reference and one reference from another Car object.
![]() |
Figure 6.3 Memory model after three Car objects are created and their anotherCar reference pointing to each other
After line 9, the three root references are made null. Figure 6.4 shows memory model when listing 6.3 is executed completely. As soon as the three root references beetle, bug and funcar are made null, the three Car objects become unreachable from the current Tester program.

Figure 6.4 Memory model after root references of three Car objects are made null
After execution of listing 6.3, these three Car objects are garbage even if they have references to each other. These Car objects have references, but they are from objects which themselves are unreachable. Therefore all three objects are unreachable form root references. Whenever garbage collector runs, it will pick them for garbage collection.
|
|
These types of unreachable objects are said to form an island of objects. This metaphor is helpful in understanding the unreachability of such objects from the root references. A program may have an island of two or more objects. |