Runtime data areas
- Java course
- Expert
- Lesson 5/46
- 5 min
Learn stack, heap and metaspace.
Runtime data areas
The JVM stores runtime data in separate data areas. The main ones are the heap (objects), the stack (method frames), Metaspace (class metadata) and the program counter (PC register).
The heap holds all class instances and arrays; it is shared and managed by the GC. The stack is per-thread; each method call pushes a frame. The frame holds local variables and the operand stack.
Metaspace holds class and method metadata. The PC register tracks which instruction the thread is running.
The stack frame
Each method call pushes a frame onto the stack. The frame contains three components: local variables, the operand stack and the method exit section.
When the method returns, the frame is popped from the stack. The stack is per-thread; therefore two threads' local variables do not mix. Stack overflow occurs in deep recursion.
Practice Print the thread name
Define a Main class. In main, print the value of Thread.currentThread().getName() with System.out.println. (The main thread's name is 'main'.)
Starter code
public class Main {
public static void main(String[] args) {
// Print the current thread's name
}
}Sample solution
public class Main {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
}
}Expected output
main
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Thread call
Thread t = Thread.____();
System.out.println(t.getName());
Thread t = Thread.currentThread();
System.out.println(t.getName());
Explanation: currentThread() returns the current thread.
2 What kind of data does the heap hold?
- Local variables
- Class instances and arrays Correct answer
- Instructions
- Thread states
Explanation: The heap holds all objects and arrays; it is managed by the GC.
3 Match the data areas
| Term | Meaning |
|---|---|
Heap |
Objects and arrays |
Stack |
Method frames |
Metaspace |
Class metadata |
PC register |
Current instruction |