After they are done doing processing, these objects are then garbage collected. After garbage collection process, the Operating System claims back the resources allocated to these objects which will be further used by new objects.
Below are the phases on which a Java object goes through out its life cycle:
1. Class Loading
Before creating object from a class, the class should be loaded to memory from the disk. The java class loader loads the class file to memory.
When class is loaded?
- when first time the object is being created.
- any static field or method is accessed first time.
2. Static initializers
Java looks for any static initializers and initializes the static fields which are part of the class and not part of a specific instance of the class (object).
3. Object creation
Object is an instance of the class. It is created in below situations:
- Declaration: when you declare object e.g. ClassA objA;
- Instantiation: when new is used to allocate new object in heap memory e.g. new ClassA();
- Initialization: new object is constructed e.g. ClassA();
4. Usage of the object
at this stage, programs could use the object either by accessing the fields or calling methods.
5. Cleanup
This is the last phase of the Java objects where they get recycled and the memory is claimed by the OS.
what happens on destruction?
- Object is removed from the memory.
- Java drops its internal references to this object.
- Garbage Collection (GC) , runs which frees objects which are not needed any more i.e. there are no references to this object.
- Finalization: GC gives objects a last chance opportunity to cleanup any other resources by calling its finalize() method.
when it happens?
- when object goes out of the scope. i.e. {...objA...}, here } becomes scope. at this time, Java run time checks for the references and lets GC recycle this object.
- when number of references to this object in java run time memory becomes zero (0).
- when object is explicitly set to null i.e. objA = null;, GC is called
- finalize() method is explicitly called.