Explain the Java memory model: heap, stack, metaspace and garbage collection.
Answer
- Heap: where all objects live; shared by all threads; divided into young generation (new objects, collected often and cheaply) and old generation (survivors, collected less often).
- Stack: one per thread; holds method frames with local variables and references.
- Metaspace: class definitions and metadata (outside the heap, grows with native memory).
- GC: finds objects no longer reachable from roots (stack variables, static fields) and frees them. Common collectors: G1 (default), ZGC, Parallel.
- Common errors:
OutOfMemoryError: Java heap space (heap full or leak), StackOverflowError (deep or infinite recursion).
Practice this question in Repaso