Java – Garbage Collection
In Java, objects are created dynamically using new operator. It becomes necessary to destroy objects whose work has finished but still acquired memory because it will cause memory shortage problem for further newly creating objects and the application will stop by throwing error OutOfMemoryError.
In old languages like C++ dynamically created objects are needed to destroy manually by using delete operator which results in a headache for the programmer.
To avoid this problem Java introduced a new technique called Garbage Collection, to destroy useless objects and get back memory occupied by them.
Garbage collection technique uses the Garbage Collector (it is a daemon thread) to collect/destroy the useless objects and regain (make free) the memory.
Useless objects are those objects which have completed their work and did not have a reference.
Garbage collector is completely controlled by JVM. It can’t be predicted that when the garbage collector will destroy the useless objects. Also, it is not possible to predict the number of useless objects destroyed by the garbage collector.
Different ways to make an object eligible for garbage collection
1) By assigning a reference one object to another object
2) By assigning a null to the reference
3) By creating anonymous object
By assigning a null to the reference
If we assign a null to the reference of any object, then that object is eligible for garbage collection.
Car c = new Car(); c = null; // eligible for garbage collection
By assigning a reference to another object
If the reference of one object refers to another object.
Car c1 = new Car(); c1 = new Car();
Car c1 = new Car(); Car c2 = new Car(); c1 = c2;
By creating anonymous object
The Anonymous object is ready for garbage collection just after its one-time use.
Requesting JVM manually, to invoke the garbage collector
We all know that JVM invokes garbage collector implicitly to collect useless object whenever it feels the necessity. But some time programmer may feel the necessity of making memory free from useless objects, at that time programmer can request JVM to invoke garbage collector by calling the gc() method. But still, it can’t be guaranteed that JVM will invoke garbage collector instantly.