'Java garbage collector - When does it collect?

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?



Solution 1:[1]

  • It depends on way program JIT compiled.
  • From outside we cannot definitely tell when it will run.
  • It follows some algorithm which depends on that particular GC.
  • Java virtual machine runs on the client machine with some virtual memory in case of windows default is 4GB. It also depends on that free virtual memory at that particular time.

You can try this small program to check behavior of GC

public class GCTest {

   final int NELEMS = 50000;

   void eatMemory() {

      int[] intArray = new int[NELEMS];

      for (int i=0; i<NELEMS; i++) {
        intArray[i] = i;
      }

   }

   public static void main (String[] args) {

      GCTest gct = new GCTest();

      // Step 1: get a Runtime object
      Runtime r = Runtime.getRuntime();

      // Step 2: determine the current amount of free memory
      long freeMem = r.freeMemory();
      System.out.println("free memory before creating array: " + freeMem);

      // Step 3: consume some memory
      gct.eatMemory();

      // Step 4: determine amount of memory left after consumption
      freeMem = r.freeMemory();
      System.out.println("free memory after creating array:  " + freeMem);

      // Step 5: run the garbage collector, then check freeMemory
      r.gc();
      freeMem = r.freeMemory();
      System.out.println("free memory after running gc():    " + freeMem);
   }
}

possible output -- May be different in your case

free memory before creating array: 4054912
free memory after creating array:  3852496
free memory after running gc():    4064184

Check this link http://www.devdaily.com/java/edu/pj/pj010008/

Solution 2:[2]

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  
    

Solution 3:[3]

It depends a lot on what garbage collector you're actually using, how its tuned, and a whole lot of inputs.

For a run down of the HotSpot Garbage Collector (the common one that comes with Java) and how it's tuned, you can check out this link

Solution 4:[4]

This completely depends on the actual JVM and what it chooses to do, and is basically out of your hands as a programmer. Greybearded die-hard experts may want to tell the JVM they know better, but for mere mortals this should be considered black magic better left alone.

What should concern you is if it can keep up with the rate that your programs creates and discards objects. If not your whole program is halted while global cleaning up occurs. That turns out to very bad response times, but happens rarely for modern JVM's on modern computers.

If you are curious about what happens in your program and when, then investigate the "jvisualvm" tool in the recent versions of the Java 6 JDK. It is really great for peeking inside.

Solution 5:[5]

The garbage collector runs when it needs resources and on a regular basis that you able to influence by telling when is a good time to spend CPU on collecting, using System.gc()

You can help the garbage collector by nulling references explicitly, for instance by giving your objects init() methods that allocate resources and cleanup() methods that explicitly clean up those resources and nulling their references. By nulling references yourself you prevent tye garbage collector from having to find clusters of obects that have to more paths to a root.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Xinus
Solution 2 LogicLight123
Solution 3 tschaible
Solution 4 Thorbjørn Ravn Andersen
Solution 5 rsp