CAP477 · Unit 5: Concurrency and I/O
Memory model and garbage collection
8 practice questions
Key points
- Heap for objects (young/old), stack for frames, metaspace for class data
- Eligible = unreachable; cycles are collectable
- System.gc() is a hint
- OutOfMemoryError (heap) vs StackOverflowError (stack)
The JVM divides memory into areas:
- Heap: all objects and arrays, shared by all threads, managed by the garbage collector. Divided into a young generation (new objects, minor GC) and an old generation (long-lived, major GC).
- Stack: one per thread; each method call pushes a frame with local variables (primitives and references) and is removed on return. Too deep recursion causes
StackOverflowError. - Metaspace (method area): class metadata, static variables, constants.
- PC register / native method stack.
Reference variables live on the stack (if local) while the object lives on the heap. Java passes references by value.
Garbage collection: an object is eligible when it is no longer reachable from any live thread's roots (locals, statics, active threads). Assigning null only removes one reference: with int[] b = a; a = null; the array stays alive because b still refers to it. Cycles do not prevent collection: two objects pointing at each other are collected once nothing outside reaches them (Java uses reachability, not reference counting).
System.gc() is only a request; the JVM decides. finalize() is deprecated and unreliable: use try-with-resources or Cleaner. Runtime reports availableProcessors(), maxMemory(), totalMemory(), freeMemory().
Reference strength: strong (default, never collected while reachable), SoftReference (cleared when memory is low; caches), WeakReference (cleared at the next GC once only weakly reachable), phantom.
Errors: OutOfMemoryError when the heap is exhausted (new int[Integer.MAX_VALUE] fails with "Requested array size exceeds VM limit"); StackOverflowError for runaway recursion. Both are Errors.
Exam pitfall: setting a variable to null does not free memory immediately; it only makes the object collectable when no other references remain.
Try two questions
Which reference type is cleared at the next garbage collection once the object is only weakly reachable?
- None; references are never cleared
- WeakReference
- SoftReference
- Strong reference
Show the answer
B. SoftReference is cleared only under memory pressure; WeakReference at the next collection.
Where are Java objects allocated?
- The heap
- The thread stack
- The metaspace
- The CPU registers
Show the answer
A. Locals and frames live on the stack; objects live on the heap.