preface
Welcome to our GitHub repository Star: github.com/bin39232820… The best time to plant a tree was ten years ago, followed by now
omg
There’s no escaping the Java virtual machine, so this series is a must, because if you’re building your Java knowledge base, you’ll know exactly how to do it. I have my own little plan for learning the JVM, starting with the JVM, and then programming Java files into.class files. And then how does the Java virtual machine load the.class file, and once it’s loaded into the virtual machine, how does that data get stored in the Java Virtual machine, and once it’s stored we know that Java automatically collects garbage, unlike C++, so we definitely have to know the garbage collection algorithm and the garbage collector, Finally to a real Java system JVM tuning, this is what I intend to talk about this series, and then most of my classes can refer to Zhou Zhiming’s in-depth understanding of the Java virtual machine
What is the JVM
The JVM, short for Java Virtual Machine, is a specification for computing devices. The JVM is an imaginary computer that is implemented by emulating various computer functions on an actual computer. The Java virtual machine consists of a set of bytecode instructions, a set of registers, a stack, a garbage collection heap, and a storage method field. The JVM shields platform-specific information, allowing Java programs to run unmodified on multiple platforms by generating object code (bytecode) that runs on the Java VIRTUAL machine. The JVM actually ends up interpreting bytecodes as platform-specific machine instructions when it executes them, which is why Java is cross-platform.
JDK JRE JVM
JDK=JRE+ some tools. JRE contains JVM(Java Virtual machine).
JVM Overview
The JVM in general is made up of
- ClassLoader Subsystem
- Runtime data area
- Execution engine
- Memory recovery
- Class file structure
Each of these five components is so important that if you want to understand the JVM and learn about JVM tuning, you have to eat them one by one
What is the class loading mechanism
The exact words from the book:
The virtual machine loads the data describing the Class from the Class file to the memory, verifies the data, transforms and initializes the data, and finally forms Java types that can be directly used by virtual machines. This is the Class loading mechanism of virtual machines
The timing of class loading
The life cycle of a class begins when it is loaded into virtual machine memory and ends when it is unloaded from memory
- loading
- validation
- To prepare
- parsing
- Initialize the
- use
- uninstall
There are seven stages
Understand class loading in three words
First of all class refers to. Class file Class, so how do you generate this file?
- Java code compilation
- It was a.class file
- Dynamic proxy generation
And so on and so forth
So what does the word load mean
The local.class file is loaded into the method area of the JVM memory through the Class loader, and the data area is accessed through this object
- Gets the binary byte stream that defines a class by its fully qualified name
- Convert the static storage structure represented by this byte stream into a binary byte stream for the method area
- The method area in memory generates the java.lang. Class object of this Class, which acts as the entry point for each data access of this Class
There are five cases that must be initialized
Java does not specify life time for the first phase of class loading, but the virtual machine has strict specifications for the initialization phase
- When the new keyword is encountered
- When you use the Reflect package method
- When initializing a class, the parent class must be initialized first
- When the virtual machine starts, the main method class is loaded
- When using dynamic language support in 1.7
Validation phase
It is divided into the following samples
- File format validation to verify that the current byte stream is recognized by the JVM
- Metadata validation, verification of its parent class, its inheritance, is abstract class and so on
- Bytecode verification to verify whether the logic is reasonable
- Validation by reference verifies that the corresponding data can be found through the generated Class object
Preparation stage
The preparation phase is the phase that formally allocates memory and sets initial values for class variables, all of which will be allocated in the method area. There are several points to note about this phase:
Static class variables are allocated, not instance variables, which are allocated in the Java heap along with the object when it is instantiated.
2. The initial value set here is usually the default zero value of the data type (such as 0, 0L, NULL, false, etc.) rather than the value explicitly assigned in Java code.
Suppose a class variable is defined as:
Public static int value = 3;
The initial value of the value variable after the preparation phase is 0, not 3, because no Java methods have been executed yet, and the putStatic instruction that assigns value to 3 is stored in the class constructor () method after the program is compiled. Therefore, assigning value to 3 will only be performed during initialization.
The following table lists all the basic data types in Java and the default zero values for the Reference type:
Here are some other points to note:
- For basic data types, class variables (static) and global variables are assigned a default value of zero if they are used without an explicit assignment, while – for local variables, an explicit assignment must be made before they are used, otherwise they will fail at compile time.
- Constants that are both static and final must be explicitly assigned at declaration, otherwise they will not pass compilation. A constant that is only final can be explicitly assigned at declaration time or at class initialization. In general, it must be explicitly assigned before use and will not be given a default zero value.
- For reference data types, such as group references and object references, if they are directly used without explicit assignment, the system will give them the default zero value, namely NULL.
- If you do not assign values to the elements of the array when the array is initialized, the elements will be assigned a default value of zero based on the corresponding data type.
If a class field has a ConstantValue property in its field property table, that is, modified by both final and static, the variable value is initialized to the value specified by the ConstValue property in the preparation phase.
Parsing stage
The parsing phase is the process by which the virtual machine replaces symbolic references in the constant pool with direct references
Class loader
From a Java virtual machine perspective, there are only two different class loaders:
- Startup class loader: it is implemented in C++ (this is limited to Hotspot, the default virtual machine after JDK1.5, many other virtual machines are implemented in the Java language) and is part of the virtual machine itself.
- All other classloaders: these classloaders are implemented in the Java language, independent of the virtual machine, and all inherit from the abstract java.lang.ClassLoader class, which needs to be loaded into memory by the launcher ClassLoader before it can load other classes.
From a Java developer’s point of view, class loaders can be broadly divided into the following four categories:
- Start the class loader (C implementation)
- Extended ClassLoader
- Application loader (ClassLoader)
- Custom loader (ClassLoader)
The hierarchy of these loaders is shown in the figure below:
Parental delegation model
This hierarchical relationship between class loaders is called the parent delegate model. The parent delegate model requires that all class loaders have their own parent class loaders except the top-level Bootstrap ClassLoader. The parent-child relationship between classloaders here is generally implemented not as inheritance, but as composition.
Parents delegate the working process of the model
If a class receives a class-loading request, it does not load the request itself. Instead, it delegates the request to the parent ClassLoader and passes it layer by layer until it reaches the Bootstrap ClassLoader. Only if the parent class loader is unable to load the request will the child loader attempt to load it itself.
Code implementation of the parent delegate model
The code implementation of the parent delegate model is concentrated in the loadClass() method of java.lang.classLoader.
- First check if the class is loaded. If not, the loadClass() method of the parent class loader is called.
- If the parent class loader is empty, the startup class loader is used as the parent by default.
- If the parent class fails to load, throw a ClassNotFoundException and call your own findClass() method.
LoadClass source code is as follows:
protected synchronized Class<? > loadClass(String name, Boolean resolve) throws ClassNotFoundException {//1 First check whether the Class is loaded Class c = findLoadedClass(name); if (c == null) { try { if (parent ! = null) {//2 calls the loadClass() method of the parent class loader if no; c = parent.loadClass(name, false); } else {//3 If the parent class loader is empty, the startup class loader is used as the parent by default; c = findBootstrapClass0(name); }} catch (ClassNotFoundException e) {//4 If (ClassNotFoundException e) {// 5 If (ClassNotFoundException e) { }} if (resolve) {//5 call your own findClass() method. resolveClass(c); } return c; }Copy the code
Custom class loaders
class NetworkClassLoader extends ClassLoader { * String host; * int port; * * public Class findClass(String name) { * byte[] b = loadClassData(name); * return defineClass(name, b, 0, b.length); * } * * private byte[] loadClassData(String name) { * // load the class data from the connection * . . . *} *}Copy the code
This is the official example
Break the parent delegate
The parent delegate model solves the problem of the uniformity of each class loader to load the base class. That is, the more basic classes are loaded by the higher loader. What if you need to call back user code in the loaded base class, and the top-level class loader doesn’t recognize that user code? This is where the parent delegate model needs to be broken.
Java’s default thread context class loader is the System Class loader (AppClassLoader).
// Now create the class loader to use to launch the application
try {
loader = AppClassLoader.getAppClassLoader(extcl);
} catch (IOException e) {
throw new InternalError(
"Could not create application class loader" );
}
// Also set the context class loader for the primordial thread.
Thread.currentThread().setContextClassLoader(loader);
Copy the code
The above code is taken from Launch(), the no-parameter constructor of sun.misc.launch.
With thread-context classloaders, you can use thread-context classloaders to load classes in the execution thread instead of the parent delegate chain mode.
A typical example would be to load a third-party library JNDI implementation through a thread context, without relying on a parent delegate.
Most Java App servers (JBoss, tomcat.) The contextClassLoader is also used to process the Web service.
At the end
Today the class loading mechanism is well talked about, so that we are more familiar with the loading process, for Java development is good
Daily for praise
Ok, everybody, that’s all for this article, you can see people here, they are real fans.
Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article
Six pulse excalibur | article “original” if there are any errors in this blog, please give criticisms, be obliged!