The virtual machine
What is a virtual machine?
A program that simulates a computer and executes a series of virtual computer commands.
classification
System VMS
The simulation of physical computer provides a software platform which can run the operating system completely
Program virtual machine
Software designed specifically to execute a computer program, such as bytecode executed by the JVM, is its instructions
The Java virtual machine
What is?
A Java virtual machine is a virtual computer that runs Java bytecode. It can run independently. The Java bytecode may not be compiled from the Java language, but can be executed as long as it complies with JVM specifications
What’s the use?
The Java Virtual machine is the runtime environment for Java bytecode, and the JVM is responsible for loading the bytecode into the JVM and interpreting or compiling it into machine instructions on the corresponding platform. Each Java instruction is clearly defined in detail in the JVM specification, such as how to fetch numbers, how to handle operands, where to put the results, etc
The characteristics of
- A compilation executes everywhere
- Automatic memory management
- Automatic garbage collector
The place of the JVM in the computer architecture
The JVM sits on top of the operating system and has no direct interaction with the hardware
The overall structure of the JVM
The overall structure of HotSpot
Java code executes the process
The architectural model of the JVM
The Java compiler enters two kinds of instruction streams
Stack-based instruction set architecture
- Simple design and implementation, suitable for resource-constrained systems
- Avoid register allocation problem; Use zero address instruction mode to assign
- The instruction stream is mostly zero-address instruction, and its execution depends on the operation stack. The instruction set is smaller and the compiler is easier to implement
- No hardware support is required and portability is better
Register-based instruction set architecture
- Performance is good
- The instruction set architecture is hardware dependent and has poor portability
- It takes less time to complete an operation
HotSpot VM follows the instruction set architecture summary: cross-platform, small instruction set, multiple instructions, and poor performance compared to register architecture
The lifecycle of the JVM
Start the
This is done by bootstrap Class Loader to create an initial class, which is determined by the virtual machine implementation.
perform
- Money runs when the program begins to execute, and stops when the program ends
- When a Java program is executed, it is actually executed by a process called the Java Virtual Machine.
The end of the
- The program completes normally
- The program encountered an exception or error during execution that resulted in an abnormal termination
- The Java VIRTUAL machine process is terminated due to an operating system error
- A thread calls the Exit method of the Runtime class or the System class, or the HALT method of the Runtime class, and the Java security manager also allows the exit or HALT operation.
The history of the JVM
Sun Classic VM
- Java 1.0 was released by Sun in 1996. It was the world’s first commercial Java virtual machine. It was completely phased out in JDK1.4.
- This virtual machine only provides the interpreter (low execution efficiency).
- If a JIT compiler is required, it needs to be plugged in, and once it is used, the JIT takes over the execution system of the virtual machine. The interpreter stops working. This means that the interpreter and compiler cannot work at the same time.
- Hotspot has this virtual machine built in
Exact VM
- Fixed the previous virtual machine issue, which is available in jdk1.2
- Exact Memory Management: What type of data can be directed to a specific location in Memory by a VM
- Hot spot detection
- Compilers and interpreters mix working modes
5 was only used briefly on Solaris, and the other platforms were still classic VMS
HotSpot VM
- The default VIRTUAL machine of the JDK
- Use the counter to find the code with the most compile value, triggering either just-in-time compilation or on-stack replacement
- The compiler and interpreter work together to balance optimal program response time with optimal execution performance.
JRockit
- Focus on server-side applications
- There is no internal parser implementation and it is all compiled and executed by the just-in-time compiler.
- Fastest JVM in the world
J9
- Close to the HotSpot
- Excellent performance in IBM’s own products
Class loading subsystem
The JVM structure
The class loader subsystem
- Responsible for loading Class files from the file system or network. Class files have specific file identifiers at the beginning of the file.
- The ClassLoader is only responsible for loading the class file, and it is up to the execution engine to decide whether it can be run
- The loaded class information is stored in a piece of memory called the method area. In addition to Class information, the method area stores runtime constant pool information, possibly including string literals and numeric constants. (This constant information is a memory map of the constant pool portion of the Class file.)
The process of class loading
The bytecode file is loaded by the JVM(class loader) into the method section of the runtime data section. The bytecode file is called the DNA metadata template (metadata), and the.getClassloader () method of the metadata is called to get its corresponding class loader. Call the constructor of the metadata to get its instance object in the heap space, and the corresponding object can call the.getClass() method to get the corresponding metadata.
Three steps in the class loading process
loading
- Gets the binary byte stream that defines a class by its permission fully qualified name
- Transform the static storage structure represented in this byte stream into the runtime data structure of the method area
- Generate a java.lang.Class object in memory that represents the Class and serves as the method area for the Class’s various data access points.
How to load a. Class file
- The local file
- The network environment
- Compressed package
- Computational generation (reflection)
- Generated from other files (JSP)
- From an encrypted file
link
- Verify
Ensure that the information contained in the byte stream in the byte file meets the requirements of the VIRTUAL machine and does not harm the virtual machine. This includes * file format verification * metadata verification * bytecode verification * symbol reference verification
- Prepare for
Allocate memory for this class variable and set default values note
- Modifying static variables with final is not included here, because final is assigned at compile time
- There is no instance variable allocation initialization, class variables are allocated in the method area, and instance variables are allocated to the Java heap along with the object
- Resolve a reference in the code to establish a connection
Initialize the
- The initialization phase is the execution of the class constructor method Clinit ()
- This method does not need to be defined and is a combination of the statements in the static code block and the assignment actions of all class variables that the Javac compiler automatically collects in a class.
- The order of instructions in the constructor methods is executed in the order in which the statements appear in the source file.
- Clinit (), unlike the class’s constructor, does not generate this method without static variables (the constructor is init from the virtual machine perspective)
- If the class has a parent class, the JVM guarantees that the parent class’s Clinit () will complete before the subclass’s Clinit () executes.
- The JVM guarantees that a class’s Clinit () method is locked synchronously in multiple threads.
It is possible to assign first and then declare because space is allocated for class variables in the preparation phase of class loading and default values are set, and assignment takes place during initialization.
Classification of class loaders
The JVM class loader supports two types
- BootStrap ClassLoader
- User-defined ClassLoader
Custom classloaders. The JVM defines all classloaders derived from the abstract ClassLoader as custom classloaders.
- The most common class loaders fall into three categories
- BootStrap ClassLoader
- Extension ClassLoader
- System ClassLoader
The relationship between the above three plus custom classloaders is inclusive rather than top-down. It’s not an inheritance.
Loaders used by different classes
- User-defined classes are loaded using the system class loader by default
- The core classes of the system are loaded using the boot class loader
Start the ClassLoader (BootStrap ClassLoader)
- Implemented in C/C++ and nested within the JVM.
- It is used to load Java’s core libraries (JAVA_HOME/jre/lib/rt.jar, resources.jar, or Sun.boot.class.path) to provide classes that the JVM itself needs
- Does not inherit from java.lang.ClassLoader and has no parent loader
- Loads extension classes and application classloaders and specifies them as parent classloaders.
- For security reasons, BootStrap starts the class loader to load only classes whose package names start with Java, Javax, and Sun
A built-in loader of the VM
- Extension ClassLoader
- Java language, implemented by sun.misc.Launcher$ExtClassLoader
- Derived from the ClassLoader class
- The parent class loader is the initiator class loader
- Load the libraries from the directory specified by the java.ext.dirs system property, or from the JRE /lib/ext subdirectory (extension directory) of the JDK installation directory. If user-created jars are placed in this directory, they will also be automatically loaded by the extended class loader.
- Application class loader (System class loader, AppClassLoader)
- Java programming
- Derived from this
- The parent class loader is the extension class loader
- It is responsible for loading the class libraries under the path specified by the environment variable classpath or the system property java.class.path
- Class loading is the default class loader in a program, and it is generally used to load classes in Java applications
- The class loader can be obtained by using the ClassLoader#getSystemClassLoader() method
User-defined class loaders
Why do I need a custom class loader?
- Isolation load class
- Modify the class loading method
- Extended load source
- Preventing source code leakage
User-defined class loader implementation steps
- Inherit the abstract java.lang.ClassLoader class and implement your own ClassLoader to meet some special needs
- Prior to JDK1.2, when customizing classloaders, you needed to inherit the ClassLoder class and rewrite the loadClass() method, but after 1.2, unlike before, it is recommended to write the custom classloading logic in the findClass() method
- If you don’t have overly complex requirements, you can inherit the URLClassLoader class directly. This avoids having to write the findClass() method and get the byte stream code yourself, making custom classloader writing much simpler
ClassLoader
Abstract classes. All classloaders inherit from classLoaders (except for starting classloaders)
How to obtain a ClassLoader
Parent delegation mechanism
The Java VIRTUAL machine loads class files on demand and generates class objects when the class needs to be used. And when a class file is loaded, the JVM uses parent-delegate mode, a task-delegate mode in which requests are handed over to the parent class.
The working principle of When a classloader receives a classloading request, if there is a parent classloader, it needs to delegate the request to the parent class. If the parent class can complete the request, the parent class will complete it. After the request is completed, it will not send the request. If not, the request is sent until the final load itself.
Example 1 Because of the parent delegate mechanism, the String core API that’s being loaded here has no main method in it
Example 2 The interface is loaded by the bootstrap class loader, and the implementation classes of the specific interface are loaded by the system class loader
Advantages of the parent delegation mechanism
- Avoid reloading classes
- Ensure program security, prevent core API tampering
Sandbox security mechanism
The protection of Java core source code through parental delegation mechanism is sandbox security mechanism. The example in Example 2 illustrates that the system does not crash due to malicious injection.
Q&A
Two necessary conditions in the JVM to indicate whether two class objects exist in the same class. The full class name of the class must be identical, including the package name. 2. The ClassLoader (referring to the ClassLoader sample object) that loads the class must be identical. That is, even if two classes in the JVM come from the same Class file and are loaded by the same virtual machine, the two objects are not equal as long as they are loaded by different classloaders. References to classloaders The JVM must know whether a type is loaded by a boot loader or by a user loader. If a type is loaded by a user class loader, the JVM stores a reference to that class loader in the method area as part of the type information. When resolving a reference from one type to another, the JVM needs to ensure that the classloaders for both types are the same.
Java programs use classes in active and passive ways
The difference is whether or not this will result in the initializer being used actively
- Example of creating a class
- Accesses or assigns a value to a static variable of a class or interface
- Call a static method of a class
- reflection
- Initialize a subclass of a class
- Classes that are identified as startup classes when the Java virtual machine starts
- JDK7 begins to provide dynamic language support:
Java. Lang. Invoke. MethodHandle example analysis results
Runtime data area
The JVM defines several types of runtime data areas that the program uses during execution, some of which have the same lifecycle as the JVM and others that correspond to threads. Shared between threads: heap, off-heap memory (permanent generation or meta-space, code cache)
The overall structure
There are two main sections based on thread usage
Thread exclusive area (program execution area)
Thread shared area (program storage area)
thread
In HotspotJvm, each thread maps directly to a local thread of the operating system. When a Java thread is ready, an operating system native thread is created at the same time. After the Java thread completes execution, the local thread also recycles. The operating system is responsible for scheduling all threads to any available CPU. Once the local thread initializes successfully, it calls the run() method in the Java thread. In Java, even if the user does not define a thread, there are many threads running during the runtime. These threads are created by the main thread.
- Virtual machine threads
- Periodic task thread
- The GC thread
- Compilation thread
- Signal scheduling thread
Program Counter (PC Register)
Purpose: Stores the address pointing to the next instruction
What is a PC register?
- Is a small, almost negligible amount of memory, and is the fastest storage area.
- In the SPECIFICATION of the JVM, each thread has its own program counter, which is thread-private and whose lifetime is consistent with that of the thread.
- There is only one method executing per thread at any one time, which is called the current method. The program counter stores the JVM instruction address of the Java method being executed by the current thread; If it’s a native method, this is undetermined.
- A program control flow indicator that performs basic functions such as branching, looping, jumping, exception handling, thread recovery, and so on.
- The bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to be executed
- It is the only area in the JVM that does not specify any GC, OOM(garbage collection, overflow) situations
Q&A
- What is the use of using PC registers to store bytecode addresses?
- Why use a PC register to record the execution address of the current thread?
The execution engine needs to know where to start because the program is constantly switching threads during execution. 2.
- PC registers are set to be thread private?
In order to be able to record the address of the current bytecode instructions being executed by each thread, because of the CPU time-slice rotation mechanism, there must be frequent interruptions and recoveries in the process of multithreading execution. In order to recover the scene, each thread generates its own program counter after creation.