|
The process of garbage collection does not necessarily happen as soon as the object becomes unreachable. Just as the garbage you create in your house is not picked up the moment you create it, the garbage collection does not occur every time some object becomes garbage. The garbage collector is part of the JVM and therefore the JVM decides when to execute it to perform the garbage collection. The JVM, at its own discretion may run the garbage collection if the memory is running low. Since you do not know exactly when JVM will decide to do garbage collection, you (as a programmer) can never be sure as to when it will take place. Later in this chapter, we will see how you can request the JVM to do a garbage collection. But there is absolutely no guarantee whether the JVM will grant your request. So the best possible answer to the question “when the object is garbage collected?” is “sometime after it becomes unreachable”. Note that garbage collector makes no guarantees that the unreachable object will even be collected. You can only be sure that its memory will be released back to the heap whenever it is garbage collected.
|
|
Garbage collection is done only for memory on the heap. Therefore the heap is also called the garbage collectible heap. Since only objects are created on heap, only objects are eligible for garbage collection. |