Garbage Collection

Garbage collection is the process of automatically detecting memory that is no longer in use, and allowing it to be used again. Java employs garbage collection to free memory that has been used by objects, saving programmers having to explicitly dispose of them.

In Java, as the developer does not explicitly remove the memory in the program code, the garbage collector finds the unnecessary objects and removes them.

It provides the following benefits:-

1. Enables you to develop your application without having to free memory.

2. Allocates objects on the managed heap efficiently.

3. Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.

4. Provides memory safety by making sure that an object cannot use the content of another object.

Garbage collection occurs when one of the following conditions is true:-
i The system has low physical memory.

ii. The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This means that a threshold of acceptable memory usage has been exceeded on the managed heap. This threshold is continuously adjusted as the process runs.

iii The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

Process of Garbage Collection can be define in two ways:-
1. Young Generation
2. Old Generation

1.Young Generation
Most of the newly created objects are located here. Since most objects soon become unreachable, many objects are created in the young generation, then disappear. When objects disappear from this area, we say a "minor GC" has occurred.
Old generation :
The objects that did not become unreachable and survived from the young generation are copied here. It is generally larger than the young generation. As it is bigger in size, the GC occurs less frequently than in the young generation. When objects disappear from the old generation, we say a "major GC" (or a "full GC") has occurred.
GC Area and Data Flow
permanent generation from the chart below is also called the "method area," and it stores classes or interned character strings. So, this area is definitely not for objects that survived from the old generation to stay permanently. A GC may occur in this area. The GC that took place here is still counted as a major GC.
Garbage Collection Are and Data Flow