Hi All,
This is the first question in Dan's Single Topic Exam of GC.
class B {
private String name;
public B(String s) {name = s;}
public void finalize() {System.out.print(name);}
}
class E {
public static void m() {
B x1 = new B("X"), y1 = new B("Y");
}
public static void main(String[] args) {
m(); System.gc();
}}
Which of the following could not be a result of attempting to compile and run the program?
a. Prints: XY
b. Prints: YX
c. Prints: XXYY
d. Nothing is printed.
e. None of the above
Answer given is
1 c Prints: XXYY
The finalize method of each instance can only run once; so X or Y can never be printed more than once. The instances referenced by x1 and y1 become eligible for garbage collection when method m returns; so both could be finalized at that time, but there is no guarantee that they will be. Even though System.gc is invoked in the main method, there is no guarantee that the garbage collector will run at that time. If the garbage collector does run before the program terminates, then the name of each object could be printed at most one time. The order in which the names are printed depends on the order in which the objects are finalized. If the garbage collector does not run, then nothing will be printed.
---------------------------------------------------------------------------
Now as he has Explained the finalize method of each intance can run only once if it runs then assuming it runs (in this case) the answer should be
a. Prints: XY
or as explained as
"The order in which the names are printed depends on the order in which the objects are finalized. "
answer would be
b. Prints: YX
But in case it would be C.
So I think the answer given is wrong. What do u all think ??
Thanks in advance.