Skip to Content
bytegarden

Java Virtual Machine (JVM)

  • A virtual machine within your computer
  • Responsible for executing Java bytecode
  • Acts as an intermediary between bytecode and the hardware

Key Features of JVM

  • Platform Independence: JVM allows Java programs to be executed on any device or operating system (WORA - Write Once, Run Anywhere)
  • Memory Management: JVM manages memory through a process called garbage collection, which automatically deletes unused objects
  • Security: JVM provides a secure execution environment by verifying bytecode before execution

JVM Architecture

  • Class Loader: Loads class files into memory. Object of that class also loaded in heap area. Supports Reflection API class loader image
    • Application Class Loader: Loads user-written application classes
    • Bootstrap Loader: Loads Java SE classes (runtime classes)
    • Extension Class Loader: Loads runtime environment classes
    • Verify: Checks if bytecode is valid and secure
    • Prepare: Allocates memory for static variables (not stored in stack or heap)
    • Resolve: Handles actual linking process
  • Bytecode Verifier: Ensures the loaded bytecode is valid and does not violate Java’s security constraints
  • Interpreter: Executes bytecode instructions directly
  • Just-In-Time (JIT) Compiler: Converts bytecode into native machine code for better performance
  • Image of JVM architecture:
    JVM Architecture

Memory Structure

Everything in Java is inside classes

The JVM divides runtime memory into areas. The main ones:

  1. Method Area: per-class data such as class structure and method bytecode (in HotSpot, Metaspace since Java 8)
  2. Stack: one per thread; a new frame for each method call, holding its local variables and parameters
  3. Heap: all objects and arrays (created with new), cleaned up by the Garbage Collector. The String pool is also on the heap (since Java 7)
class First {
    public static void main(String[] args) {
        int x, y, z;           // Stack variables
        String str;            // Reference in Stack
        str = new String();    // Object in Heap
    }
}

For details, see Stack and Heap Memory.