Friday, August 11, 2017

Garbage Collection


Garbage Collection is process of reclaiming the runtime unused memory automatically.

In other words, it is a way to destroy the unused objects.

Advantages of Garbage Collection

  1. Programmer doesn't need to worry about dereferencing an object.
  2. It is done automatically by JVM.
  3. Increases memory efficiency and decreases the chances for memory leak.



How can an object be unreferenced

There are many ways:

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

By nulling a reference

Employee e=new Employee();  

e=null; 

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  

By anonymous 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.

 protected void finalize()

{

 

Important Points to Remember

  1. finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
  2. finalize() method is declare as proctected inside Object class.
  3. finalize() method gets called only once by a Daemon thread named GC (Garbage Collector)thread



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.

Syntax

public static void gc(){} 



example

No comments:

Post a Comment