Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java Code or applications. It converts Java bytecode into machines language. JVM is a part of Java Runtime Environment (JRE). In other programming languages, the compiler produces machine code for a particular system. However, Java compiler produces code for a Virtual Machine known as Java Virtual Machine.
JVM 包含什么?
由三部分组成:
ClassLoader
RuntimeMemory/DataArea
Execution Engine
类加载器——ClassLoader
加载机制:按需动态加载,并采用 双亲委派机制
加载过程:
Loading:加载,getClassLoader()
Linking:链接
Verification:校验阶段,校验文件是否符合 JVM 规范
Preparation:静态变量赋为默认值
Resolution
Initializing:初始化,调用静态代码块,将静态变量赋值为初始值
分类:
Bootstrap:加载核心类,由 C++ 实现,通过 getClassLoader() 方法,结果为 Null
The interpreter reads and executes the bytecode instructions line by line. Due to the line by line execution, the interpreter is comparatively slower.
缺点是:不管一个方法被重复调用多少次,每一次都需要 Interpreter 来解释运行
JIT 编译器(JIT Compiler)
The Execution Engine first uses the interpreter to execute the byte code, but when it finds some repeated code, it uses the JIT compiler.
The JIT compiler then compiles the entire bytecode and changes it to native machine code. This native machine code is used directly for repeated method calls, which improves the performance of the system.
Code Optimizer:optimizes intermediate code for better performance
Target Code Generator:converts intermediate code to native machine code
Profiler:finds the hotspots (code that is executed repeatedly)
垃圾收集器(Garbage Collector)
The Garbage Collector (GC) collects and removes un referenced objects from the heap area. It is the process of reclaiming the runtime unused memory automatically by destroying them.
JNI——Java Native Interface
At times, it is necessary to use native (non-Java) code (for example, C/C++). This can be in cases where we need to interact with hardware, or to overcome the memory management and performance constraints in Java. Java supports the execution of native code via the Java Native Interface (JNI).
JNI acts as a bridge for permitting the supporting packages for other programming languages such as C, C++, and so on.
Native Method Libraries
Native Method Libraries are libraries that are written in other programming languages, such as C, C++, and assembly. These libraries are usually present in the form of .dll or .so files. These native libraries can be loaded through JNI.