X

Play AlgoQuiz

Rate Us :



Share with Friends :

Menu

Garbage Collection :

In old languages like C++, creation and destruction of object is responsibility of programmer. Usually programmer takes very much care while creating objects and neglecting destruction of useless objects. Due to this ignorance at certain point of time for the creation of the new object sufficient memory may not be available and entire program will be collapsed due to memory problems.

But in Java, programmer is responsible only for creation of objects and he is not responsible for destruction of the useless objects. Sun Microsystem provided garbage collector which is always running in the background for the destruction of useless objects. Due to this facility chance of failure of Java program with memory problem is very rare. Hence, the main objective of garbage collector is to "destroy useless objects".

The various ways to make an object eligible for garbage collector :

Even though programmer is not responsible to destroy useless objects, it is always a good programming practice to make an object eligible for garbage collector if it is no longer required.

An object is said to be eligible for garbage collector if it doesn't contain any references.

The following are various possible ways to make an object eligible for garbage collector :

Nullifying the reference variable :

If an object is no longer required then assign 'null' to all its references then automatically that object is eligible for garbage collector.

Algo a1 = new Algo();
Algo a2 = new Algo();

a1 = null; // first object eligible for garbage collector

a2 = null; // second object eligible for garbage collector

Methods for requesting JVM to run garbage collector :

Whenever we are making an object eligible for garbage collector then it may not be destroyed by garbage collector immediately either whenever JVM runs garbage collector then only the object will be destroyed.

We can request JVM to run garbage collector programmatically but whether JVM will accept the request or not, there is no guarantee for that. The following are various ways for requesting JVM to run garbage collector :

  • By System class :-

System class contains a static method gc() for this.

System.gc();
  • By Runtime class :-

By using Runtime object, a Java application can communicate with JVM. Runtime class is singleton class hence we can't create Runtime object by using constructor. We can create a Runtime object by using factory method 'getRuntime()'.

Runtime r = Runtime.getRuntime();

Once we got Runtime object we can apply the following methods on the object :-

  • freeMemory() - Returns free memory in the heap area.

  • totalMemory() - Returns total memory of the heap area.

  • gc() - For requesting JVM to run garbage collector.

Example :

import java.util.*; class Example { public static void main(String [ ] args) { Runtime r = Runtime.getRuntime(); System.out.println(r.totalMemory()); // Output : 61341696 System.out.println(r.freeMemory()); // Output : 60691448 for(int i = 0 ; i < 1000 ; i++) { Date d = new Date(); d = null; } System.out.println(r.freeMemory()); // Output : 60691448 r.gc(); System.out.println(r.freeMemory()); // Output : 61099216 } }

Note :

gc() method present in System class is a static method where as gc() method present in Runtime class is instance method and it is recommended to use System.gc() method.


Finalization :

Just before destroying an object, garbage collector always call finalize() method to perform clean-up activities on the object. finalize() method declare in Object class with the following declaration :

protected void finalize() throws Throwable

Garbage collector always call finalize() method on the object which is eligible for garbage collector, just before destruction of objects the corresponding class finalize() method will be executed. If String object is eligible for garbage collector then String class finalize() method will be executed but not Example class finalize() method.

Example :

class Example { public static void main(String [ ] args) { String s = new String("Algo"); s = null; System.gc(); System.out.println(s); } public void finalize() { System.out.println("Example class finalize() method"); } }

Output :

null

In the above example, String object is eligible for garbage collector. Hence, String class finalize() method got executed which has empty implementation. If we replace String object with Example object then Example class finalize() method will be executed.

Example :

class Example { public static void main(String [ ] args) { Example e = new Example(); e = null; System.gc(); System.out.println(e); } public void finalize() { System.out.println("Example class finalize() method"); } }

Output :

null Example class finalize() method

If we call finalize() method explicitly then it will be executed just like a normal method call and object won't be destroyed but before destruction of an object garbage collector always call finalize() method.

Example :

class Example { public static void main(String [ ] args) { Example e = new Example(); e.finalize(); e = null; System.gc(); System.out.println(e); } public void finalize() { System.out.println("Example class finalize() method"); } }

Output :

Example class finalize() method null Example class finalize() method

If we are calling finalize() method explicitly and while executing that finalize() method if any Exception raised which is uncaught then the program will be terminated abnormally.

If garbage collector calls finalize() method and while executing that finalize() method if any Exception raised which is uncaught then JVM simply ignores that uncaught Exception and rest of the program will be executed normally.

Example :

class Example { public static void main(String [ ] args) { Example e = new Example(); e.finalize(); // Line 1 e = null; System.gc(); System.out.println(e); } public void finalize() { System.out.println("Example class finalize() method"); System.out.println(10 / 0); } }

Output :

Runtime Exception : ArithmeticException: / by zero

If we are not commenting Line 1 then we are calling the finalize() method explicitly and the program will be terminated abnormally. If we are commenting Line 1 then garbage collector calls finalize() method and raised ArithmeticException is ignored by JVM.

Example :

class Example { public static void main(String [ ] args) { Example e = new Example(); // e.finalize(); // Line 1 e = null; System.gc(); System.out.println(e); } public void finalize() { System.out.println("Example class finalize() method"); System.out.println(10 / 0); } }

Output :

null Example class finalize() method

Note :

On any object, garbage collector calls finalize() method only once.

The behaviour of garbage collector is vendor dependent and hence we can't answer the behaviour of the garbage collector like :

  • When JVM runs garbage collector exactly ?

  • What is the algorithm followed by garbage collector ?

  • In which order garbage collector destroys the object ?

  • Whether garbage collector destroys all the eligible objects or not ?

  • We can't tell exact algorithm followed by the garbage collector but in most of the case it is Mark or Sweep algorithm.

Memory leak :

If an object having the reference then it is not eligible for garbage collector, even though we are not using that object in our program still it is not destroyed by the garbage collector. Such type of object is called memory leak (i.e. memory leak is the useless object which is not eligible for garbage collector). We can resolve memory leak by making useless objects to be eligible for garbage collector explicitly and by invoking garbage collector programmatically.



X

MiniDoll :

MiniDoll is an application to learn with fun. You can play it to solve some tricky questions related to Java Programming. Either enjoy playing it alone or discuss with your friends to solve it. It is a simple approach to learn by solving questions. This application has different topics of Java and each topic is divided into three phases. Start solving from initial topic to final topic and by the end of every topic you can boost your concept of that topic.