Java Garbage Collection

In java, garbage means unreferenced objects. The unused memory automatically collected by which process is known as Garbage Collection. That means it is a process to destroy the unused memory. In JAVA it is performing automatically. So in JAVA memory management is better

Advantage of Garbage Collection

  1. It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  2. 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:

  1. By nulling the reference
  2. By assigning a reference to another
  3. By annonymous object etc.

1) By nulling a reference:

Customer c=new Customer();  
c=null;

2) By assigning a reference to another:

Customer c1=newCustomer();  
Customer c2=new Customer();  
c1=c2;//now the first object referred by c1 is available for garbage collection 

 

3) By annonymous object:

new Customer();

finalize() method

when 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:
protected void 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.
public static void 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.

Example

public classGarbageDemo{  
 public void finalize()
{
System.out.println("Silan Technology");
}  
 public static void main(String[] args)
{  
  GarbageDemo ob1=newGarbageDemo();  
  GarbageDemo ob2=new GarbageDemo();  
  ob1=null;  
  ob2=null;  
  System.gc();  
 }  
}  

Output
object is garbage collected
object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment