Tuesday, March 15, 2016

What is garbage collection in Java

Dear Folks !
This post has a very interesting topic for discussion, i.e Garbage collection in Java...

We know memory management is a crucial aspect in programming. In programming languages like C/C++, programmer can allocate and de-allocate memory at run-time of the program. 

Perhaps, you are aware, memory for local variable, is cleared by the system automatically, once the variable goes out of scope.(i.e when control exits the block{} in which it is created).But, when memory  is allocated at run-time from Heap section, it must be de-allocated by the programmer itself.

We programmers are human beings, obviously have the tendency of forgetting things. So what happens if we forget to free/de-allocate the memory which we have allocated at run-time, somewhere in the program. This image makes it clear.


Did you get the point ? 
Yes ! You are right ! When the same program is run multiple times, every time memory is allocated but not made free, so this makes the memory full and make it crash !

How good it is ! if some one manages this de-allocation task from our side...
Be happy ! Garbage Collector is there for you ! Let's see how it does !

Garbage collector is program(thread),running in the background, to find or locate unreachable objects in heap. An object is said be unreachable if it has no reference in stack to refer it. So any object which is no more referenced, is claimed back by the garbage collector. Thus making the memory free for reuse.
Before,claiming the memory back, the garbage collector calls finalize() method to relinquish any resource held by the object(like file,socket etc).

Let me demonstrate it with this example...
class A
{ --------- }

class DemoGC
{
 public static void main(String arg[])
{
 A a1 = new A();
 A a2 = new A();
 A a3 = new A();
-----
----- 
A a4,a5,a6;
a4 = new A();
a5 = new A();
a6 = new A();
-----
-----
a1 = a4; 
/* here the address of a4 overwrites address of a1-- This is how, a1 becomes unreachable */
a2 = a5; 
/* here the address of a5 overwrites address of a2-- This is how, a2 becomes unreachable */
a3 = a6; 
/* here the address of a6 overwrites address of a3-- This is how, a3 becomes unreachable */
----
}

This could be well understood with help of this image...
This is how garbage collector manages the de-allocation of memory. It could be called explicitly by calling  method java.lang.System.gc().

Did you like it ? Please reply/comment/suggest...
Let's share it to grow and to grow to share !



No comments:

Post a Comment