When Is The Object Eligible For Garbage Collection?

The object will not become a candidate for garbage collection until all references to it are discarded. An object is marked as eligible to be garbage collected when it can no longer be accessed, which can happen when the object goes out of scope. It can also happen when an object’s reference variable is assigned an explicit null value or is reinitialized. If an object cannot be accessed, that means any live thread is not able to access it through any reference variable that is used in a program. Generally, an object becomes eligible for garbage collection in Java on following cases:
  1. Any instances that cannot be reached by a live thread.
  2. Circularly referenced instances that cannot be reached by any other instances.
  3. If an object has only lived weak references via WeakHashMap it will be eligible for garbage collection.
  4. The object is created inside a block and reference goes out scope once control exit that block.