JVM Architecture
TL;DR
- The Java Virtual Machine (JVM) is the engine that drives Java code.
- It converts Java bytecode into machine-specific language, making Java “Write Once, Run Anywhere” (Platform Independent).
- Its architecture consists of 3 main subsystems: Class Loader Subsystem, Runtime Data Areas (Memory), and the Execution Engine.
Concept
When you compile a .java file, javac produces a .class file containing Bytecode. This bytecode is not native machine code (like C++ produces). The CPU cannot understand it.
Instead, you must install a JVM on your specific Operating System (Windows, Linux, Mac). The JVM acts as a translator.
- Class Loader: Reads the
.classfiles from the hard drive, links them, verifies their security, and loads them into RAM. - Runtime Data Areas: This is the JVM’s memory architecture. It divides RAM into specific sections: Method Area (Metaspace), Heap, Stack, PC Registers, and Native Method Stacks.
- Execution Engine: Takes the bytecode loaded in memory and executes it. It contains an Interpreter (reads line by line), a JIT Compiler (optimizes hot code into native machine code), and the Garbage Collector.
Examples
public class JvmArchitectureDemo {
public static void main(String[] args) {
// 1. ClassLoader loads JvmArchitectureDemo.class into the Method Area
// 2. Execution Engine starts executing 'main' via the Interpreter
// 3. 'person' object is created on the HEAP (Runtime Data Area)
// 4. The reference variable 'person' is stored on the STACK
Person person = new Person("Alice");
// 5. If this method is called thousands of times, the JIT Compiler
// will compile it into native machine code for maximum performance
person.sayHello();
}
}
Interview Questions
Q: What does “Write Once, Run Anywhere” mean?
A: It means that Java source code is compiled into an intermediate form called Bytecode. Bytecode is platform-agnostic. You can compile a Java program on a Windows machine, send the resulting .class file to a Linux server, and it will execute flawlessly. The catch is that you must have a platform-specific JVM installed on the Linux server to translate that bytecode into Linux-specific machine instructions.
Q: What is the difference between JVM, JRE, and JDK?
A: - JVM (Java Virtual Machine): The abstract specification and actual running instance that executes bytecode. It contains the Execution Engine and Memory Management.
- JRE (Java Runtime Environment): The physical installation on a computer. It contains the JVM, plus all the standard Java Class Libraries (e.g.,
java.lang.String,java.util.ArrayList) needed to run a program. - JDK (Java Development Kit): The full developer toolkit. It contains the JRE, plus development tools like the compiler (
javac), archiver (jar), and debugger (jdb).