What is garbage collection?
- The applications created to acquire memory. Memory management includes deallocating this acquired resources and acquiring them. This is done by the garbage collector and this concept of automatically reclaiming the memory is called Garbage Collection.
- It manages the allocation and release of memory for your application.
- It performs a collection in order to free some memory.
- It determines the best time to perform a collection which is based upon the allocations being made.
- When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.Advantages of Garbage Collection:
1. It removes the unreferenced objects from heap memory. It makes the java memory efficient.
2. Releasing the memory space is automatically done by the garbage collector.
- The garbage collector of JVM collects only those objects that are created by 'NEW' keyword. So if you have created any object without 'NEW', you can use finalize() method to perform cleanup processing.
- The gc() method (garbage collector() method) is used to invoke the garbage collector to perform cleanup processing.
- The gc() method is found in System and Runtime classes.Example:
public static void gc()