Java Garbage Collection

Garbage Collection in Java

Java has built-in facility to re-claim unwanted memory, this is known as garbage collection. Garbage collector plays its role if there is any memory defficiency. Usually an object no longer referenced, for example when you assign with null, it could be ready for garbage collection. In java all objects are created in heap memory, whereas primitive type and object reference are placed in stack memory. Object class has defined finalize() method that is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

The purpose of Java Garbage Collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.

Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Java Garbage collection is an automatic process and can't be forced.

Java Garbage Collection program

class GC
{
public static void main(String args[]){
MyObj obj = new MyObj();
obj=null;
System.gc();
}
}

class MyObj
{
public MyOb(){
System.out.println("Object created");
}
protected void finalize()
{
System.out.println("Garbage collector in action");
}
}

Garbage collection will start immediately upon request of System.gc(). Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

No comments:

Post a Comment