There are a couple of different algorithms that the GC can use to find out what to clean out. Some of them are more aggressive in keeping the memory usage as low as possible and others are trying disturb the program as little as possible. But they all work more or less in the same way.
The GC goes through all the object references and marks objects that it thinks could be cleaned out. It also searches for islands of object references, such as an ArrayList that has no reference to it. When it has found an object an marked it X number of times, it sweeps it away.
If you google for 'java garbage collection tutorial' then you can spend a couple of hours reading about different algorithms and how they work. If you master this, you don't have to do a lot of coding, since you will be the "tuning master" ;)
Joined: Feb 11, 2011
@Bear Bibeault Thanks,
@ Ove Lindström Yaa I will try to find such tutorials and study. Thanks though.
in your example mybox is not object, it is reference of the object which is created by (new Box();)
means mybox is holding bits internally which point to the object,
and gc is the process of cleaning the object from memory which are not used longer,
String s1 ="Abc"
s1 = "xyz;
after line 2 the object which is created internally as new String("Abc")
will not have any live reference so it will available for garbage collection, because s1 is now holding the object new String("xyz")
I think you may be mistaken about garbage collection for Strings; I think (but I am not certain) that String literals are "live" as long as the classes they are referred to from are "live". Do a search for "Strings, literally" and you will find a useful JavaRanch Journal article which will probably explain that to you.