Stack Heap Lazy instantiation Flashcards
When is stack and heap used
Stack memory stores the active methods and their local variables.
Heap memory stores all created objects
What is garbage collection
Items in the Heap which are no longer referenced from the stack are eligible for garbage collection.
Java offers garbage collection, i.e., the garbage collector runs in the background on its own thread.
2 errors related to memory
Out of memory:
if heap memory is full, it throws java.lang.OutOfMemoryError.
Stack overflow:
when stack memory is full, Java runtime throws java.lang.StackOverFlowError.
Often this is due to infinite (or very high numbered) recursion, where each frame in the recursion has some local memory requirements.
Caching data and lazy instantiation
Caching data is to prevent wasteful re-computation.
Lazy instantiation is to compute only the things that we
need, when we need them, but leveraging caching to not waste this computation.
Lazy initialization is particularly useful for GUIs which take a long time to construct.