What is Heap space? - When a Java program is executed JVM gets some memory from RAM. JVM uses this memory for all its need and part of this memory is known as Java Heap Space. Whenever you create object using new operator or by any another means, object is allocated memory from Heap. When object is dead / garbage collected, memory goes back to the Heap.
You can change size of heap space by using JVM options -Xms and -Xmx. Xms denotes starting size of Heap while -Xmx denotes maximum size of Heap.
Java Heap space is divided amongst following three parts:
- Young Gen [This space is made up of Eden space and Survivor spaces]
- Old Gen
- Perm Gen
Garbage Collection Process
- All new objects created in your program gets first allocated to Young Gen's Eden Space. Once Eden space fills up, minor Garbage Collection is triggered. Live/Referenced objects are then moved to first survivor space. Unreferenced/dead objects are deleted and Eden space is cleared.
At the next minor GC, the same thing happens for the eden space. Unreferenced objects are deleted and referenced objects are moved to a survivor space. However, in this case, they are moved to the second survivor space (S1). In addition, objects from the last minor GC on the first survivor space (S0) have their age incremented and get moved to S1. Once all surviving objects have been moved to S1, both S0 and eden are cleared. Notice we now have differently aged object in the survivor space.
At the next minor GC, the same process repeats. However this time the survivor spaces switch. Referenced objects are moved to S0. Surviving objects are aged. Eden and S1 are cleared.
After a minor GC, when aged objects reach a certain age threshold (8 in typical scenarios) they are promoted from young generation to old generation.
As minor GCs continue to occure objects will continue to be promoted to the old generation space.
Eventually, a major GC will be performed on the old generation which cleans up and compacts that space.
JVM expands Heap in Java some where near to Maximum Heap Size specified by -Xmx and if there is no more memory left for creating new object in java heap, JVM throws java.lang.OutOfMemoryError and your application dies.
This is nicely explained here with graphical representation of Heap Space.