Sub topic 1
Where the JVM Keeps Your Data
Prerequisites
You should know basic Java syntax, objects, references, and how to run a Java program from the command line.
Where the JVM Keeps Your Data
The Java Virtual Machine (JVM) divides runtime data into areas with different jobs:
| Area | Typical contents |
|---|---|
| Heap | Objects and arrays |
| Java stacks | Method frames, local variables, and references |
| Metaspace | Class metadata |
| Code cache | Compiled machine code |
The heap is shared by threads. Each thread has its own Java stack. Metaspace stores information about loaded classes, such as method definitions and field descriptions.
Stack Frames and the Heap
A stack frame is the memory used by one active method call. It contains local variables, method arguments, and temporary values. A local variable holding an object usually holds a reference, not the object itself.
The object is stored on the heap. Several references can point to the same object.
public class MemoryInfo {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long megabyte = 1024 * 1024;
System.out.println("Maximum heap: " + runtime.maxMemory() / megabyte + " MB");
System.out.println("Committed heap: " + runtime.totalMemory() / megabyte + " MB");
System.out.println("Free committed heap: " + runtime.freeMemory() / megabyte + " MB");
}
}-Xmx sets the maximum heap size. -Xms sets the initial heap size. These values affect the heap, not every memory area used by the JVM.
Reachability and GC Roots
Garbage collection (GC) reclaims objects that can no longer be reached. The collector starts from GC roots, which include active stack references, static fields, running threads, and some JVM-managed references. It follows references from those roots.
An object is garbage when no path from any GC root reaches it. Setting a variable to null can remove one path, but collection is not immediate or guaranteed at a particular time.
> callout note > A garbage collector manages unreachable objects. It does not repair a program that keeps unnecessary objects reachable.
How Collectors Reclaim Memory
Collectors commonly mark live objects, sweep unreachable objects, or copy live objects into another region. Compaction moves live objects together to reduce fragmentation. Copying works well when most objects are short-lived.
Modern collectors combine these techniques and divide the heap by object age. Short-lived objects are collected frequently; long-lived objects are promoted. The exact behavior depends on the selected collector and JVM version.
Exercise
If a local variable is removed but a static list still contains the object, can the object be collected?
Show answer
No. The static list is reachable from a GC root, so the object remains reachable.