i

JAVA Complete Course

Garbage Collection

Garbage collection is java is an automatic process of memory management. In java objects are saved in heap memory. It is the part of memory which mainly is used for program. During the program execution there will be some objects with may not be needed anymore. The garbage collection is a mechanism which takes care of cleaning up memory from classes which are no longer needed. This is an automatic process so that it does not require marking objects for deletion from developers. The process of cleaning up memory (garbage collections) takes places on Java Virtual Machine.

Let’s shortly describe how heap is divided:

The memory where objects are saved, heap, has 3 sections:

Young Generation: this is the memory place where recently created objects are placed. The Young Generation is also divided into two parts: the first is Eden space, where we have recently created objects, and second is Survivor spaces, in which we have objects from Eden space and these are objects which passed one garbage collections cycle.

Old Generation: comparing to young generation memory segment, here we have objects which are longer-lived.

Permanent Generation: This part of memory contains metadata such as classes and methods. No longer used classes can be removed from this part of memory by garbage collector.

One thing to remember is that we can push our program at any place to call System.gc() which is actual call of garbage collector but it never guaranties the immediate cleaning of the memory.