Understanding JVM and JRE

Overview

JVM (Java Virtual Machine) and JRE (Java Runtime Environment) are two fundamental components of Java that make it platform-independent and powerful. Understanding them is crucial for understanding how Java works.

JVM (Java Virtual Machine)

What is JVM?

JVM is a virtual machine that runs Java bytecode. It is:

  • An abstract computing machine
  • Platform-specific (different for Windows, Mac, Linux)
  • The engine that executes Java programs
  • Part of JRE

Key Characteristics

  1. Platform-Dependent: Different JVM for each OS
  2. Executes Bytecode: Runs .class files
  3. Provides Runtime Environment: Manages program execution
  4. Virtual: Doesn’t physically exist, implemented in software

How JVM Works

Execution Flow:

Java Source Code (.java)

  Java Compiler (javac)

  Bytecode (.class)

  Class Loader → Loads classes into JVM

  Bytecode Verifier → Checks code safety

  Interpreter/JIT Compiler → Converts to machine code

  Execution Engine → Runs the program

  Operating System

JVM Architecture

1. Class Loader Subsystem

Functions:

  • Loading: Reads .class files
  • Linking: Verifies and prepares classes
  • Initialization: Initializes static variables and blocks

Types of Class Loaders:

  • Bootstrap Class Loader: Loads core Java classes (rt.jar)
  • Extension Class Loader: Loads extension classes
  • Application Class Loader: Loads application classes from classpath

2. Memory Areas (Runtime Data Areas)

a) Method Area:

  • Stores class structure, method data, field data
  • Contains static variables
  • Shared among all threads
  • Also called Metaspace (Java 8+)

b) Heap:

  • Stores all objects and arrays
  • Shared among all threads
  • Garbage Collection happens here
  • Divided into:
    • Young Generation: New objects
    • Old Generation: Long-lived objects
    • Permanent Generation: Metadata (before Java 8)

c) Stack:

  • Each thread has its own stack
  • Stores local variables and method calls
  • LIFO (Last In First Out) structure
  • Stores primitive values and references

d) Program Counter (PC) Register:

  • One per thread
  • Stores address of current instruction
  • Points to next instruction to execute

e) Native Method Stack:

  • For native (non-Java) methods
  • Stores native method information

Memory Layout:

┌──────────────────────────────────┐
│        Method Area               │ ← Class data, static variables
├──────────────────────────────────┤
│           Heap                   │ ← Objects, Arrays
├──────────────────────────────────┤
│    Thread 1 Stack   │ Thread 2  │ ← Method calls, local variables
├─────────────────────┼───────────┤
│    PC Register 1    │  PC Reg 2 │ ← Current instruction
├─────────────────────┼───────────┤
│ Native Method Stack │  Native   │ ← Native methods
└─────────────────────┴───────────┘

3. Execution Engine

Components:

a) Interpreter:

  • Reads bytecode line by line
  • Converts bytecode to machine code
  • Slower execution
  • Used when method is called first time

b) JIT (Just-In-Time) Compiler:

  • Compiles frequently used code (hot spots) to native code
  • Stores compiled code for reuse
  • Improves performance significantly
  • Used for repeated method calls

c) Garbage Collector:

  • Automatically removes unused objects
  • Frees memory
  • Runs automatically
  • Different algorithms: Serial, Parallel, G1, ZGC

Execution Process:

Bytecode

Interpreter → Execute (first time)

JIT Compiler → Optimize hot spots

Native Code → Faster execution

4. Java Native Interface (JNI)

  • Allows Java to interact with native libraries (C/C++)
  • Enables platform-specific functionality
  • Used for system calls and hardware access

JVM Languages

JVM can run programs written in:

  • Java
  • Kotlin
  • Scala
  • Groovy
  • Clojure
  • JRuby

All compile to Java bytecode!


JRE (Java Runtime Environment)

What is JRE?

JRE is a software package that provides the environment to run Java applications. It includes:

  • JVM: To execute bytecode
  • Core Libraries: Java API classes
  • Supporting Files: Configuration files, property files

JRE Components

1. JVM:

  • Executes Java bytecode
  • Core component of JRE

2. Java Class Libraries:

  • Pre-written Java classes
  • Standard API: java.lang, java.util, java.io, etc.
  • Ready-to-use functionality

3. Class Loader:

  • Loads classes into memory
  • Part of JVM

4. Bytecode Verifier:

  • Ensures code safety
  • Checks for security violations

5. Interpreter/JIT Compiler:

  • Executes bytecode

JRE vs JDK

JRE (Java Runtime Environment):

  • For: End users
  • Purpose: Running Java applications
  • Contains: JVM + Libraries
  • Cannot: Compile Java code
  • Use case: Running .class or .jar files

JDK (Java Development Kit):

  • For: Developers
  • Purpose: Developing Java applications
  • Contains: JRE + Development Tools (javac, debugger, etc.)
  • Can: Compile and run Java code
  • Use case: Writing, compiling, and running Java programs

Relationship:

JDK = JRE + Development Tools
JRE = JVM + Class Libraries

Analogy:

  • JRE is like a media player (plays content)
  • JDK is like a video editor (creates and plays content)

JDK vs JRE vs JVM Comparison

FeatureJVMJREJDK
Full FormJava Virtual MachineJava Runtime EnvironmentJava Development Kit
PurposeExecute bytecodeRun Java appsDevelop Java apps
PlatformPlatform-specificPlatform-specificPlatform-specific
ContainsExecution engineJVM + LibrariesJRE + Dev tools
For WhomCore componentEnd usersDevelopers
Can RunBytecodeJava programsJava programs
Can CompileNoNoYes (javac)
SizeSmallestMediumLargest
Example ToolInterpreter, JITClass librariesjavac, jar, javadoc

Detailed Relationships

Hierarchy:

┌─────────────────────────────────────────┐
│              JDK                        │
│  ┌───────────────────────────────────┐  │
│  │           JRE                     │  │
│  │  ┌─────────────────────────────┐  │  │
│  │  │         JVM                 │  │  │
│  │  │                             │  │  │
│  │  │  - Class Loader             │  │  │
│  │  │  - Bytecode Verifier        │  │  │
│  │  │  - Execution Engine         │  │  │
│  │  │  - Runtime Data Areas       │  │  │
│  │  └─────────────────────────────┘  │  │
│  │                                   │  │
│  │  + Java Class Libraries           │  │
│  │    (java.lang, java.util, etc.)   │  │
│  └───────────────────────────────────┘  │
│                                         │
│  + Development Tools                    │
│    (javac, jar, javadoc, debugger)      │
└─────────────────────────────────────────┘

Why JVM is Platform-Independent?

It’s NOT! JVM itself is platform-dependent.

Explanation:

  • Different JVM for Windows, Mac, Linux
  • Each JVM is specifically built for its OS
  • But all JVMs understand the same bytecode
  • Java programs are platform-independent because:
    • Compiled to universal bytecode
    • Same bytecode runs on any JVM
    • JVM translates bytecode to OS-specific code

Analogy: Bytecode is like a universal music file format (like MP3). JVM is like a music player (different player for each device, but all play the same MP3).

How Java Achieves Platform Independence

Traditional Languages (C++):

C++ Source → Compiler → Windows.exe (only Windows)
C++ Source → Compiler → Linux binary (only Linux)

Java:

Java Source → Compiler → Bytecode (universal)
Bytecode → Windows JVM → Runs on Windows
Bytecode → Mac JVM → Runs on Mac
Bytecode → Linux JVM → Runs on Linux

JVM Specifications

Key Points:

  1. Specification: Oracle defines JVM specification

  2. Implementation: Different vendors implement it:

    • Oracle HotSpot JVM
    • IBM J9 JVM
    • OpenJDK JVM
    • GraalVM
  3. All implementations must:

    • Understand Java bytecode
    • Follow JVM specification
    • Provide same behavior

Garbage Collection in JVM

What is Garbage Collection?

  • Automatic memory management
  • Removes objects no longer in use
  • Frees memory automatically
  • Prevents memory leaks

How It Works:

  1. Mark: Identify objects in use
  2. Sweep: Remove unused objects
  3. Compact: Reorganize memory

Types of Garbage Collectors:

  1. Serial GC: Single-threaded, small applications
  2. Parallel GC: Multi-threaded, medium applications
  3. CMS (Concurrent Mark Sweep): Low pause time
  4. G1 (Garbage First): Large heaps, balanced
  5. ZGC: Ultra-low latency, huge heaps

JVM Performance Tuning

Common JVM Options:

# Set maximum heap size
java -Xmx512m MyApp

# Set initial heap size
java -Xms256m MyApp

# Set stack size
java -Xss1m MyApp

# Choose garbage collector
java -XX:+UseG1GC MyApp

Exam Tips

Key Points to Remember:

  1. JVM:

    • Executes bytecode
    • Platform-specific
    • Part of JRE
    • Provides runtime environment
  2. JRE:

    • For running Java apps
    • Contains JVM + libraries
    • For end users
    • Cannot compile code
  3. JDK:

    • For developing Java apps
    • Contains JRE + dev tools
    • For developers
    • Can compile and run
  4. Relationship: JDK ⊃ JRE ⊃ JVM

  5. Platform Independence:

    • Bytecode is platform-independent
    • JVM is platform-specific
    • Same bytecode runs on all JVMs
  6. JVM Components:

    • Class Loader
    • Memory Areas (Heap, Stack, Method Area)
    • Execution Engine (Interpreter, JIT)
    • Garbage Collector
  7. Memory Areas:

    • Heap: Objects
    • Stack: Method calls, local variables
    • Method Area: Class data
  8. Execution:

    • Bytecode → Interpreter → Machine code
    • Hot spots → JIT Compiler → Optimized code

Common Questions:

  • What is difference between JDK, JRE, and JVM?
  • How does JVM achieve platform independence?
  • Explain JVM architecture
  • What is JIT compiler?
  • How does garbage collection work?