Java Virtual Machine¶
JVM Architecture¶
JVM itself is a piece of software. It is running on the operation system to simulate a computer. It has no direct interaction with the hardware.
Java Execution:
- Firstly, Java source code will be compiled to byte code, e.g. .class files (
javac
).
decompile tool: javap, intellij plugin - jclasslib Bytecode Viewer
de-Syntactic sugar: Generic, var args, Autoboxing/unboxing, inner class, Enums, String in Switch, try resources etc. The virtual machine does not support these syntaxes, they are compiled back to the simple basic syntax structure.
- Then, Class Loader loads .class files into Runtime Data Area for execution.
Parents delegation model: Class Loaders has hierarchy. When loading a class, a class loader firstly delegates the loading to its parent class load. if the parent class loader can't load the class, the class loader then tries to load by itself.
loadClass vs forName: loadClass loads class without initialization. used for lazy loading, e.g. Spring Lazy loading. forName loads class with initialization.
- Then, Execution Engine executes commands using PC register, VMS(Java Stack) and NMS for each thread.
Interpreted Execution: byte code will be interpreted (in machine code) and executed immediately. Java uses this mode normally.
Compiled Execution: byte code will be compiled to intermediate code (platform dependent) firstly, and the intermediate code will be interpreted and executed by engine. The intermediate data works as a cache.
- Java program can invoke Native Method written by C, C++, etc. during execution.
@See JDK8 Hotspot JVM Source Code
Garbage Collection¶
Young Generation:
- Newborn objects (not very big); Survivor object who's generation doesn't exceed the age threshold (
-XX:MaxTenuringThreshold
). - unreachable objects cleaned by Minor GC using Copying (to survivor) and Clean algorithm.
- 1/3 Heap space, in which 8/10 Eden, 1/10 Survivor From, 1/10 Survivor To.
Old Generation :
- for Big objects, arrays; Long Lived Objects promoted from Young Gen, etc.
- Cleaned by Major GC using Mark and Sweep or Mark and Compact algorithms.
- 2/3 Heap space
Both Minor GC and Major GC trigger the stop-the-world pause, stopping the threads.
Full GC has no formal definition. It clean both Young Gen and Old Gen mainly when the Old Gen has no enough space.
GC optimization: aims to reduce the stop-the-world, improve throughput
Throughput == code execution time / (code execution time + GC execution time)
Through adjusting the size of Heap and its division, selecting the appropriate GC Collector (-XX:-Use<GC>
) according to different use cases.
-
https://medium.com/platform-engineer/understanding-java-memory-model-1d0863f6d973 ↩
-
https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html ↩
-
https://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html ↩
-
深入理解Java虚拟机 - 周志明 ↩
-
https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html ↩
-
剑指offer - 慕课网 ↩