A technique in Java which handles de-allocation of memory allotted for objects, automatically.
As the program runs, the execution engine of the JVM creates objects of the classes. These objects are maintained in the form of a heap (a special type of tree) & stored in the area called Java Objects Heap.
Any object which is no longer required for execution is called 'garbage'. To optimize the available memory usage, it is necessary to collect and destroy the garbage so that the heap space it occupies can be recycled and thus space is made available for subsequent new objects. This automatic cleaning of memory by destroying the unwanted objects is called garbage collection. In the JVM, a daemon thread runs as a background process, all the time, for the task of automatic garbage collection, which takes place sporadically (irregular intervals).
When an object becomes eligible for garbage collection?
- If there are no reference variables pointing to the object, this object can be garbage collected, ie., removed from memory.
In addition to automatic de-allocation, the garbage collector also moves the objects within the heap memory as the application runs to reduce heap fragmentation.
What is Heap Fragmentation?
when unreferenced objects are freed, it will result in free portions of heap memory, left in between the portions occupied by the live objects. Thus, even though there is enough total unused space in existing heap, to allocate new objects, they are not contiguous to fit in the new object. Thus the size of the heap has to be expanded to allocate space for new objects. This ever-growing heap can degrade the performance of the executing program (or) can cause the virtual machine to run out of memory. Garbage collector helps to avoid this problem by moving the objects within the heap.
Advantages of automatic garbage collection:
- programmers can spend effort in the core logic of the program and be more productive rather than analyzing the execution part and be focusing on housekeeping activities such as how to free the memory.
- Increases the security and integrity of the Java program by protecting it from accidentally (or purposely) crashing the JVM, by incorrectly freeing memory.
- JVM has to keep track of all the objects created and used. This affects the performance of the program and impacts the speed.
- Programmers in a garbage-collected environment have less control over the scheduling of CPU time devoted to freeing objects that are no longer needed.