JVM (Java Virtual Machine)
In short: The JVM is the “virtual machine” that executes Java bytecode. It makes Java platform independent: the same bytecode runs on Windows, Linux and macOS because there is a matching JVM for each system.
In more detail: The JVM behaves like a small abstract computer with its own instruction set (bytecode), its own memory model and its own memory management. It sits as a layer between the program and the operating system.
In Depth
Components of the JVM:
- Class loader: Loads
.classfiles on demand, checks them (verifier) and links them. - Memory areas: Heap (objects), stacks (per thread: calls and local variables), metaspace (class information).
- Execution engine: An interpreter runs bytecode; the JIT compiler (in HotSpot: C1 and C2) translates frequently used methods into fast machine code.
- Garbage collector: Frees memory of objects nobody points to anymore (G1, ZGC, Shenandoah …).
- Security: The bytecode verifier prevents invalid code. (The former Security Manager is deprecated.)
Important startup options:
java -Xms256m -Xmx2g -jar app.jar # initial and maximum heap size
java -XX:+UseZGC -jar app.jar # choose a garbage collector- Other languages: Kotlin, Scala, Groovy and Clojure also produce bytecode and run on the JVM.
- Several JVMs: HotSpot (default in OpenJDK), GraalVM, OpenJ9. The language is standardized, the implementation is not.
- Cost: Startup takes a bit and memory is needed for the JVM itself. In return, long-running programs are very fast after warm-up.
- Troubleshooting:
OutOfMemoryError(heap too small or a leak),StackOverflowError(recursion too deep).
See also: Runtime environments: JVM, CLR, BEAM and co., Bytecode, Garbage collector