You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Before java, we needed to allocate and de-allocate memory
malloc(), realloc(), calloc()
free()
new and destructors
If we forget, memory leaks
Java provides automatic memory management through a program called Garbage collector
"Remove objects that are not used anymore"
live object = reachable (referenced by someone else)
dead object = unreachable (not referenced from anywhere)
Based on following hypothesis
Most objects soon become unreachable
References from 'old' objects to 'young' objects only exist in small numbers
Example: cache - is probably already populated and new objects may not be added
Garbage collection
Before we start
Objects are allocated (eg: new) in the "heap" of java memory. Static members, class definitions (metadata) etc. are stored in "method area" (Permgen/Metaspace)
Garbage collection is carried out by a daemon thread called "Garbage collector"
We can not force gc to happen (System.gc())
When new allocations can not happen due to a full heap you end up with a java.lang.OutOfMemoryError heap space and a lot of other headaches
Arrays are also objects in Java
Involves:
Mark: Starts from root node of application (main), walks the object graph, marks objects that are reachable as live.
Delete/sweep: Delete unreachable objects
Compacting: Compact the memory by moving around the objects and making the allocation contiguous than fragmented
Generational collectors
Young generation
Eden space - new objects created here (Eden garden)
Survivor space from
If no more space in Eden space, small gc is kicked off
Un-reachable objects are cleaned off
reachable objects are moved here (survived gc)
Survivor to
Old (Tenured) generation
Holds objects for a long time (cache)
Major garbage collection cycle can collect this if un-reachable (major gc runs across heap - causes pauses in application)