The exact mechanism is meant to be a mystery. The JVM authors have a lot of freedom in what they can do, and developers who write code to run on the JVM don't have to worry about GC. In fact, if you knew much about GC and tried to optimize your code based on what GC is going to do, your code might be a disaster on another JVM or the next release of the JVM.
So, all those warnings aside, GC is fascinating and deeply complex. If you Google for Java Garbage Collection you'll find some details on various JVM versions with some tips about how to analyze problems and adjust tuning. I've been able to successfully ignore it except for a very few times when tuning was necessary.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I just want to know garbage collection itself involeves lots of memory , i mean to keep track of things it needs to collect and check which are the things that have no longer any refernce..etc i mean lots of stack and heap space Then why it is still considered correct me if am wrong
Most modern garbage collectors use some variant of a "mark and sweep" algorithm, which uses a single bit of storage for each memory block (each object). The heap allocator itself will use more than that, of course, so the memory usage of the collector is very modest.
There was a series on developerworks named something like Inside the IBM Garbage Collector, it was describing the logic behind the garabage collector of IBM's JVM implementation which may give you a good understanding.