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
- Programmer doesn't need to worry about dereferencing an object.
- It is done automatically by JVM.
- Increases memory efficiency and decreases the chances for memory leak.
How can an object be unreferenced
There are many ways:
- By nulling the reference
- By assigning a reference to another
- 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
- finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
- finalize() method is declare as proctected inside Object class.
- 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