Core Module
12 min forge

JVM Architecture

How Java code is executed and how memory is managed.

JVM Architecture

πŸ“˜ What is it

The JVM (Java Virtual Machine) is an abstract machine that provides a runtime environment in which Java bytecode can be executed. It follows the "Write Once, Run Anywhere" principle by translating bytecode into machine-specific instructions.

πŸ—οΈ Core Components

  1. Class Loader: Loads, links, and initializes class files.
  2. Runtime Data Areas: Memory area used by JVM during program execution.
    • Method Area: Stores class structures, metadata, and static variables.
    • Heap Area: Primary area for object allocation; managed by Garbage Collector.
    • Stack Area: Stores local variables and partial results for each thread.
    • PC Registers: Stores the address of the current execution instruction.
    • Native Method Stack: Used for native methods (written in C/C++).
  3. Execution Engine: Executes the bytecode.
    • Interpreter: Reads bytecode and executes instructions sequentially.
    • JIT Compiler: Compiles frequently used code sections into native machine code for better performance.
    • Garbage Collector (GC): Automatically deallocates memory for objects that are no longer reachable.

🧠 Memory Layout

  • Stack: Thread-safe, fixed size, stores primitives and object references.
  • Heap: Shared across threads, dynamic size, stores actual objects.

❌ Common mistakes

  • Memory Leaks: Thinking Java doesn't have memory leaks (e.g., static references holding onto large objects).
  • StackOverflowError: Excessive recursion without a base case.
  • OutOfMemoryError: Creating too many objects that exceed the heap size.