• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage collection output doubt

 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question about garbage collection. The output is 10,20,10. In the line which has an arrow, t1 is nulled before t2. so shldnt the output be something like 10,10,20 instead?
 
Javier Sanchez Cerrillo
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, the order is not guaranted in gc.
 
Dave Reinhardt
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Somewhere in SCJP it says that calling the System.gc() is just a recommendation to the JVM to clean up some garbage. So, just like threads, my guess is there is no gaurantee that the objects will be garbage collected at all, let alone in any predictable order.

Is this a question on a mock exam?

I get the second output if I do the following:
t1=null;
System.gc();
t2=null; //<-
System.gc();
 
wise owen
Ranch Hand
Posts: 2023
 
Vaibhav Chauhan
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as said that the order of finalize method is not decided....
in the following code the result is same as 10,20,10 for all the iterations and it remains same for any number of runs of the program.
Shouldn't the answer get changed to 10,10,20 for even a single time ??


 
Sathish Nagappan
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vaibhav Chauhan:
as said that the order of finalize method is not decided....
in the following code the result is same as 10,20,10 for all the iterations and it remains same for any number of runs of the program.
Shouldn't the answer get changed to 10,10,20 for even a single time ??


That again depends on the algorithm used for GC. Typical Mark and Sweep algorithms , use a generalized starting point (such as LRU or FIFO) or what ever. So it is not possible to say that the objects might get garbage collected in a particular order at all.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The order may depend on order of creating of objects, since finalizable object may be registered somewhere in JVM internally when they are created. Sun JVM uses the same mechanism for this as for soft/weak/phantom references
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic