How does garbage collection work?
StackChief LLC
Last updated on
Your thoughts?
Share your thoughts
loaded question...
GC is an automatic mechanism that will collect unused objects and free up the memory space used for these objects.
GC is done automatically. There is nothing you do as a developer to trigger this process
GC is automatic. don't worry about it. :)
GC uses a combination of algorithms (mark-sweep, copy, mark-compact) to efficiently collect unused or unreferenced objects in the heap. GC creates regions of memory blocks designated for "young" or "old" generation objects. By dividing memory based on object lifespan, the JVM can efficiently use the most appropriate algos to clean up memory in the space.
This makes java very memory-efficient without any intervention from the developer.
Research shows that over 98% of objects have a limited lifespan. Since majority of objects are short lived, these are collected in younger generation and a "copy" based approach is taken. This is because since everything is mostly dead when the GC scans it can easily copy over surviving objects to a survivor space and compact the memory space to eliminate fragmentation.