No.
An object may be garbage-colllected
even if there are references pointing to it.
The true important thing
is the fact that the object is unreachable,
not the fact that there are references to it!
E.g. Each iteration of the following program creates
a 1-million objects in a circular-list.
Each object in the list has a reference to the next one
and to the previous one.
If you launch the application with the OFF argument
then after few iteration (3 or 4 on my PC)
the memory is exausted because the garbage-collector
is never called.
If you launch the application with the NULL argument
then in each iteration the 1-million object in the
circular-list becomes unreachable EVEN IF
each one of these 1-million objects still have references to them.
In this case (objects with references to them but unreachables)
the garbage-collector may be invokec so the program never crash
for OutOfMemory exception.
Try it....
.... and learn the difference
between "unreachable" and "references to it" !
- Dario
class Java46 {
Java46 next;
Java46 prev;
Java46(int n) {
this(null);
while(--n > 0)
new Java46(this);
}
Java46(Java46 j46) {
if(j46 == null) {
next = this;
prev = this;
} else {
next = j46.next;
prev = j46;
j46.next.prev = this;
j46.next = this;
}
}
public static void main(String argv[]) {
if(argv.length != 1 ||
(! argv[0].equals("NULL") && !argv[0].equals("OFF"))) {
System.out.println("usage: java Java46 NULL|OFF");
return;
}
Java46 j[] = new Java46[1000];
for(int i=0; i<j.length; i++) {
j
= new Java46(1000*1000);
// Now there are 1 million objects
// in the circular list pointed by j.
// Each object in the circular list is pointing
// to the prev and to the next.
if(argv[0].equals("NULL")) {
j = null;
// Now the 1 million objects are not reachables
// but they still are referenced by next and prev:
// so they may be garbage-collected!
}
System.out.print(" "+i);
}
}
}