How GC works
Last updated
Was this helpful?
Last updated
Was this helpful?
Most initial objects allocated in Eden space
Young generation has two survivor spaces
Objects that survive GC get moved to the survivor space
Only one survivor space in use at a time
Objects copied between survivor spaces
Minor GC happens when Young generation is full.
A number in the green rectangle is a number of minor GCs which the object has survived.
After minor GC survivor space is swapped, Eden space is cleared and new allocations happen in Eden space.
Major GC happens when Old generation is full. It collects old and young generations (actually called Full GC).
Non realistic and idealistic usecase of one thread (just to demonstrate an idea):
After allocation of memory the pointer (arrow) just incremented (which is very quickly)
Java uses Thread Local Allocation Buffers (TLABs). Each Thread gets its own buffer in the Eden space. This buffers helps to avoid any locking mechanism (locking could have been required because many threads are sharing same heap memory and they need to allocate objects concurrently). Every thread can allocate memory just in given buffer.
Live roots are references from
track frames
static variables
JNI (Java Native Interface)
synchronisation monitors
Objects in Young Gen can be references by objects in Old Gen. And such objects should survive GC. The issue is that Young GC scans only Eden and Survive spaces for Root set references. It does not scan Old Gen.
Young GC does not scan Old Gen due to efficiency
. To fix this issue there are Card Tables.
When write to young Gen object happens (I assume from Old Gen), this write goes through Write Barrier (this is a mechanism in JVM). Write Barrier triggers code in JVM, and this code updates an entry in a table. During Minor GC this Card Table is scanned and if there were any changes for particular entry (and entry corresponds to the object in Young Gen) then object in Young Gen survives.