Garbage collection is a mechanism to remove objects from memory when they are no longer needed.
Garbage collection is carried out by the garbage collector:
finalize() Method
A constructor helps to initialize an object just after it has been created.
•In contrast, the finalize method is invoked just before the object is destroyed:
Garbage collection is carried out by the garbage collector:
Garbage Collection in Java |
- The garbage collector keeps track of how many references an object has.
- It removes an object from memory when it has no longer any references.
- Thereafter, the memory occupied by the object can be allocated again.
- The garbage collector invokes the finalize method.
finalize() Method
A constructor helps to initialize an object just after it has been created.
•In contrast, the finalize method is invoked just before the object is destroyed:
- implemented inside a class as:
- protected void finalize() { … }
- implemented when the usual way of removing objects from memory is insufficient, and some special actions has to be carried out
Simple Example of garbage collection in java
- public class SampleGarbage1{
- public void finalize(){System.out.println("object is garbage collected");}
- public static void main(String args[]){
- SampleGarbage1 s1=new SampleGarbage1();
- SampleGarbage1 s2=new SampleGarbage1();
- s1=null;
- s2=null;
- System.gc();
- }
- }