MainMenu

Home Core Java Overview Maven Tutorials

Saturday, 14 January 2017

Garbage Collection in Java with example



For Video Tutorial : Move on Youtube Channel


Note : Select the playlist as per your need & move with number sequence


Garbage collection in java with example

Garbage collection in java is a process to free the unused memory but only one type of memory can get free and this is dynamic memory allocation.
When garbage collection is performed then only reserved Tags are removed and that the data is still there untill it is overwritten by some other data.
If garbage collection is not automatic in java then a lot of out of memory problem may arise. As in java everything is based on objects and if Garbage collector is not automatic then heap area will become full and out of memory error will come.


There are two types of objects in Java 1). Reachable
2). Unreachable. Note : In java only unreachable objects are cleared by garbage collector. In java there is only four basic conditions when objects become unreachable 1). When we create object in functions other than Main
2).When we assign one object's reference id to another 3).If we set the Reference ID of an object to null
4).By making anonymous objects.
As we know that anonymous object have two main property :

1). They don't have any name
2). They can't be reused.

Example of Condition 1: In the below example we have created two objects other than main method when the execution of program will get finish then these twoo object will become unreachable & this type of condition arises in java in most of cases.

class Demo
{
int x =10;
int y = 20;
static void met1()
{
Demo obj1 = new Demo();
met2();
}
static void met2()
{
Demo obj2 = new Demo();
}
}
public class GC1
{
public static void main(String args[])
{
Demo obj3 = new Demo();
System.out.println("i am finished the variable obj1 & obj2 become " + "unreachable but the content in main is still running and in the memory");
}
}

Output ; i am finished the variable obj1 & obj2 become unreachable but the content in main is still running and in the memory.

Example of Condition 2:
class Demo
{
int x = 10;
int y = 20;
}
public class GC2
{
public static void main(String args[])
{
Demo obj1 = new Demo();
Demo obj2 = new Demo();
obj2 = obj1; // here we assigned the Reference inside obj1 to obj2.
System.out.println("i am inside the garbage collector"); }
}

Output ; i am inside the garbage collector.
Example of Condition 3:
class Demo
{
int x = 10;
int y = 20;
}
public class GC3
{
public static void main(String args[])
{
Demo obj1 = new Demo();
System.out.println(obj1.x);
obj1 = null;
}
}

Output ;
10
Example of Condition 4:
class Demo1
{
int x = 10;
int y = 20;
}
public class GC4
{
public static void main(String args[])
{
System.out.println("new Demo1().x"); //anonymous object
}
}

Output ; 10
Tags:-

Garbage collection in Java

What is garbage collection in java

Example of garbage collection in java

No comments:

Post a Comment