Automatic Garbage Collection: is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.
The basic process are as follows:
Step 1: Marking. This is the garbage collector identifies which pieces of memory are in use and which are not.
Step 2: Normal Deletion: Normal deletion removes the unreferenced objects leaving referenced objects and pointers to free space.
Step 2a: In addition to deleting unreferenced objects, we can compact the remaining referenced objects. By moving refernced object together, this makes new memory allocation much easier and faster.
The head is broken up into smaller parts or generations. The heap parts are: Young Generation, Old or Tenured Ganeration, and permanent Gneration
Young Generation: is where all new objects are allocated and aged. (Minor garbage collection)
Old Generation: store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. (Major garbage collection).
Permanent generation: contains metadata required by the JVM to describe the classes and methods used in the application.
The Generational Garbage Collection Process
1. First, any new objects are allocated to the eden space. Both survivor spaces starts out empty.
2. When the eden space fills up, a minor garbage collection is triggered.
3. Referenced objects are moved to the first survivor space. Unreferenced objects are deleted when the eden space is cleared.
4. At the next minor GC, the same thing happeneds for the eden space. In this case, they are moved to the second survivor space.
5. At the next minor GC, the same process repeats. survivor space switch. Referenced objects are moved to S0. Surviving objects are aged. Eden and S1 are cleared.
6. Promotion. when aged objects reach a certain age threshold, they are promoted from young generation to old generation.
7. continue promoted to the old generation space.
8. after cover the entire process with the young generation. Eventually, a major GC will be performed on the old generation which cleans up and compacts that space.
The more detailed explain is over there: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html
Invoke Java Garbage Collection
System.gc() method which simply a hint to the garbage collector that you want it to do a collection.
System.runFinalization() method to tell do any pending finalizers to be run for all the eligible objects for GC.
long freeMemory(): return an amount of free memory in bytes available for new objects use.
long totalMemory() to find total amount of memory in bytes available in JVM.