Saturday, January 11, 2020

Garbage Collection

Garbage Collection

Java provides automatic garbage collection and  allocates and de-allocates(free) memory so that the programmers need not bother with this task.In other words,Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.There can be some not referenced or unused objects in memory.This memory can be reclaimed and can be made available for reuse.However,Java provides automatic garbage collection, as programmers we can also enforce garbage collection in java. Automatic Garbage collection makes Java truly robust.

There are few stages in automatic garbage collection.

Marking:All references are marked on the basis of their current usage.


Normal deletion:Unused memory references are deleted and their record are maintained.

Compacting: 
Example

class Test
{
String name;
static int count=0;
Test(String name)
{
this.name=name;
count++;
System.out.println("you created "+name+" number of objects of Test are "+(count));
}
@Override
protected void finalize() throws Throwable {
super.finalize();
count--;
System.out.println(this.name+ " is finalized number of Test Objcets are "+(count)); }
}
public class Demo {

public static void main(String[] args) {
Test t1=new Test("Red");
Test t2=new Test("white");
Test t3=new Test("blue");
// objects created
t1=null; t2=null; t3=null;
//objects are set to null means they are not is use now
System.gc();
//Garbage collection is called
}
}

Output:

you created Red number of objects of Test are 1
you created white number of objects of Test are 2
you created blue number of objects of Test are 3
blue is finalized number of Test Objcets are 2
white is finalized number of Test Objcets are 1
Red is finalized number of Test Objcets are 0


Video Tutorial