Java Garbage Collection with Example

preview_player
Показать описание
Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

How can an object be unreferenced?
There are many ways:

By nulling the referenceBy assigning a reference to anotherBy annonymous object etc.

1) By nulling a reference:

Employee e=new Employee();  e=null;  

2) By assigning a reference to another:

Employee e1=new Employee();  Employee e2=new Employee();  e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:

new Employee();  

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:

protectedvoid finalize(){}  

Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

publicstaticvoid gc(){}  

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java

publicclass TestGarbage1{   publicvoid finalize(){
}   
public static void main(String args[])
{     TestGarbage1 s1=new TestGarbage1();    
 TestGarbage1 s2=new TestGarbage1(); 
  } 
 }  

Test it Now

object is garbage collected object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

-~-~~-~~~-~~-~-
Please watch: "How to online money earn from Flipkart without selling any products"
-~-~~-~~~-~~-~-
Рекомендации по теме
Комментарии
Автор

Description is also very helpful for us thanks a lot from heart😊

bhawnaassvani
Автор

please make a playlist. The explanation is too good

sambitpati
Автор

Sach m bhot mahenat kiye ho app is video ko bnanne m

Himanshu-ybkz