Java garbage collector - When does it collect?

Viewed 61794

What is it that determines when the garbage collector actually collects? Does it happen after a certain time or after a certain amount of memory have been used up? Or are there other factors?

6 Answers

When the JVM doesn't have necessary memory space to run, the garbage collector will run and delete unnecessary objects to free up memory.

Unnecessary objects are the objects which have no other references (address) pointing to them.

There are mainly 4 ways an object can eligible for garbage collection.

  1. Null Referencing

    The garbage collector can delete an object when the reference variable of the object is assigned null as its value.

        A a = new A();
        a = null;
    
  2. Re-assigning

    When another object is assigned to the reference variable of an object, the older referenced object can be deleted by the garbage collector.

      A a = new A(100);
      a =new A(200);
    
  3. Local Scope

    If an object is created inside a block, then that object will be eligible for garbage collection outside that block.

      if(condition){
    
         A a = new A();
    
      }
    
  4. Isolation

    An object can contain a reference to another object, but there must be at least one reference (address) variable for those objects in the stack, otherwise all those objects are eligible for garbage collection.

          class A{
                A r;
                A(int i){
                 //something   
               }
          } 
    
          A a1 = new A(100);
          a1.r = new A(101);
          a1.r.r = new A(102);
          a1.r.r.r = a1;
    
          a1  = null //all ojects are eligible to garbage collector  
    
Related