This is one of the Questions from Marcus Green's mock exam. please go through the code...
What will happen when you compile and run the following code?
The answer given is Compilation and eventually multiple outputs of "finalizing a Box"
Is it because since the while condition is true, it goes on creating new objects of type Box, and this continues, and at some point of time as these objects have no references, they will be eligible for garbage collection, so the finalize method is executed on these objects.
Please correct me if i am wrong.
Thanks in advance. [ October 19, 2004: Message edited by: Barry Gaunt ]
I agree with you. But I am not sure as to why it will not go into a infinite loop and hence run out of memory after some time. Even though there are so many objects which are eligible for garbage collection, they are not necessarily garbage collected as soon as the object gets created, right?
... and hence run out of memory after some time. Even though there are so many objects which are eligible for garbage collection, they are not necessarily garbage collected as soon as the object gets created
Vishnu is correct.
All these objects are being created in an infinite loop. However they have no reference pointing to them, and so are ELGIBLE for garbage collection immediately after being created. (Elgible I say, not garbage collected).
The jvm certainly will perform actual garbage collection on unreferenced objects before memory becomes too low, and so in this example, memory doesn't get depleted in the infinite loop. Although unreferenced objects keep getting created, many of the previously created unreferenced objects get garbage collected (showing the output) as the loop progresses.
These unreference objects use up more and more memory and therefore give a pretty good incentive for the garbage collection to run.
Key to the answer is that while you cannot force the GC to run through code (as is well established Runtime.gc() only suggests the GC run) it is guaranteed to run before the JVM runs out of memory. Therefore it WILL run at intervals during the endless loop cleaning out all those unreferenced objects.
Maybe someone can voice in whether this is what to expect from the exam as it looks to me like the question wants to trick you into giving the wrong answer rather than test your knowledge.