Garbage collection Project


Java Garbage Collection

Click here to download eclipse supported ZIP file



In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
How can an object be unreferenced?

There are many ways:

By nulling the reference
By assigning a reference to another
By annonymous object etc.

1) By nulling a reference:

Employee e=new Employee();
e=null;

2) By assigning a reference to another:

Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:

new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:

protected void finalize(){}

Imp : The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

public static void gc(){}
Imp : Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected

Simple Example of garbage collection in java

 

    
package com.cv.java.garbagecollector;

public class TestGarbage {
  public void finalize() {
    System.out.println("object is garbage collected");
  }

  public static void main(String args[]) {
    TestGarbage s1 = new TestGarbage();
    TestGarbage s2 = new TestGarbage();
    s1 = null;
    s2 = null;
    System.gc();
  }
}


Advanced example of understanding finalize() method :

 

    
package com.cv.java.garbagecollector;

/**
 @author Chandra Vardhan
 
 */
public class FinalizeDemo {

  static FinalizeDemo s;

  public static void main(String[] argsthrows InterruptedException {
    FinalizeDemo finalizedemo = new FinalizeDemo();
    System.out.println(finalizedemo.hashCode());
    finalizedemo = null;
    System.gc();
    Thread.sleep(1000);
    System.out.println(s.hashCode());
    s = null;
    System.gc();
    Thread.sleep(1000);
  }

  public void finalize() {
    System.out.println("finalize method calls");
    System.out.println(this.hashCode());
    s = this;
  }

}


Java Runtime class

Java Runtime class is used to interact with java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory etc. There is only one instance of java.lang.Runtime class is available for one java application.

The Runtime.getRuntime() method returns the singleton instance of Runtime class.

Important methods of Java Runtime class


No.MethodDescription
1)public static Runtime getRuntime()returns the instance of Runtime class.
2)public void exit(int status)terminates the current virtual machine.
3)public void addShutdownHook(Thread hook)registers new hook thread.
4)public Process exec(String command)throws IOExceptionexecutes given command in a separate process.
5)public int availableProcessors()returns no. of available processors.
6)public long freeMemory()returns amount of free memory in JVM.
7)public long totalMemory()returns amount of total memory in JVM.



Java Runtime exec() method



 

    
package com.cv.java.garbagecollector;
/**
 @author Chandra Vardhan
 
 */
public class Runtime1 {
  public static void main(String args[]) throws Exception {
    Runtime.getRuntime().exec("notepad");// will open a new notepad
  }
}

Java Runtime freeMemory() and totalMemory() method

In the given program, after creating 10000 instance, free memory will be less than the previous free memory. But after gc() call, you will get more free memory.



 

    
package com.cv.java.garbagecollector;
/**
 @author Chandra Vardhan
 
 */
public class MemoryTest {
  public static void main(String args[]) throws Exception {
    Runtime r = Runtime.getRuntime();
    System.out.println("Total Memory: " + r.totalMemory());
    System.out.println("Free Memory: " + r.freeMemory());

    for (int i = 0; i < 10000; i++) {
      new MemoryTest();
    }
    System.out.println("After creating 10000 instance, Free Memory: " + r.freeMemory());
    System.gc();
    System.out.println("After gc(), Free Memory: " + r.freeMemory());
  }
}


Example for Runtime class and it's usage :


 

    
package com.cv.java.garbagecollector;

import java.util.Date;


/**
 @author Chandra Vardhan
 
 */
public class RuntimeDemo {

  public static void main(String[] args) {
    Runtime runtime = Runtime.getRuntime();
    System.out.println(runtime.totalMemory());
    System.out.println(runtime.freeMemory());
    for (int i = 0; i < 10; i++) {
      Date d = new Date();
      d = null;
    }//
    Runtime runtime2 = Runtime.getRuntime();
    System.out.println(runtime2.freeMemory());
    runtime.gc();
    System.out.println(runtime2.freeMemory());
  }

}


Example for finalize method and it's usage :



 

    
package com.cv.java.garbagecollector;

/**
 @author Chandra Vardhan
 
 */
public class Test {
  static int count = 0;

  public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
      Test t = new Test();
      t = null;
      ++count;
      System.gc();
    }
  }

  public void finalize() {
    System.out.println("finalize method calls : " + count);
  }
}

No comments:

Post a Comment