1. Start the VM

The Java virtual machine is started by creating an Initial Class by the Bootstrap Class Loader, which is specified by the virtual machine’s implementation.

2. Vm execution

  1. A running Java virtual machine has one clear task: execute Java programs.
  2. He runs when the program starts and stops when the program ends.
  3. When a so-called Java program is executed, the computer is really executing oneJava virtual machine process.

When we execute a simple program called Main, we actually load a lot of classes. When we add suspend code to the code, and then use the JPS instruction to check the process number (PID) of the JVM currently running during the suspend:The Main class occupies a process number independently, while other helper runtime classes are running; When the program finishes executing, the Main method naturally disappears

3. The thread

In a HotSpot virtual machine, each thread maps directly to the operating system’s native thread. When a Java thread is ready for execution, a local thread of the operating system is created at the same time. When the Java thread terminates, the local thread is reclaimed. The operating system schedules all threads to any available CPU and calls the run() method in the Java thread once the local thread is successfully initialized. Threads are divided into daemon and non-daemon threads. If only daemon threads are left in the program, the virtual machine exits.

There are many threads behind a Java program:

  • Vm threadsThe reason these operations must occur in different threads is that they all need to be done by the JVMsaferSo that the heap does not change. THE tasks performed by this thread include “stop-the-world,” garbage collection that terminates all threads, thread stack collection, thread suspension, and biased lock undo.
  • Periodic task thread: This thread isTime periodThey are commonly used for scheduling execution of periodic operations.
  • The GC threadThis type of thread pair is different in the JVMGarbage collectionBehavior provides support.
  • Compilation thread: This thread will runBytecode compilationCost of local code.
  • Signal scheduling thread: This thread receives signals that are sent to the JVM and processed within it by calling the appropriate method.
  1. JVM security point: in the virtual machineAccessibility analysisWhen the HotSpot virtual machine records where references are available at specific locations, these specific locations are called safe points. That’s the GC thing, and I’ll parse it later.

4. Class loading process

As we know, the JVM reads in the Class file for loading. The usual reads are on local disks, but in practice, Class loading supports: local, network, JAR packages, and even Class files generated by runtime calculations.

4.1 The macro process of class loading

  1. The.class file is stored on the local disk and can be thought of as a template drawn on paper by the designer. The template is eventually loaded into the JVM at execution time. From this template, the JVM can instantiate N identical instances.
  2. The.class file is loaded into the JVM, known as the DNA metadata template, and is placed in the method area.
  3. In the.class file -> JVM -> eventually become a metadata template, this process requires oneVehicle (Class Loader)“, act as the operation of a Courier. And thisThe means of transportThat’s our main story today: the classloading subsystem.

4.2 Detailed process of class loading

4.2.1. Loading Stage (loading in a narrow sense)

The main tasks of the load phase are to read in the Class file, build the static storage structure, and generate the metadata template in memory. The detailed process is as follows:

  1. Gets the binary byte stream that defines a class through its fully qualified name.
  2. Converts the static storage structure represented by the byte stream into the runtime data structure of the method area.
  3. A java.lang.Class object that represents the Class is generated in memory and is used as an entry point for various data about the Class in the method area.

Several sources of loading:

  • The local system
  • network
  • Jars, compression packages, and so on
  • Runtime computing generation, for example: dynamic proxy technology
  • Generated by other files
  • Extract from a proprietary database. The Class file
  • Obtained from an encrypted file, a typical protection measure against Class files being decompiled

4.2.2. Link phase

The linking phase is focused on verifying the validity and accuracy of the Class file, initializing variable values for information in the Class, and executing static methods. The linking phase is divided into three smaller stages:

4.2.2.1. Verification phase

The purpose of the verification is to ensure that the byte stream of the Class file contains information that meets the requirements of the current VM, ensure the correctness of the loaded classes, and ensure the security of the VM. Include:

  • File format verification: The hexadecimal representation of the binary header of a file can be recognized by the Java virtual machineCA FE BA BE(Cafe babe).
  • Metadata validation
  • Bytecode verification
  • Symbolic reference validation

What is metadata? 【 Baidu Encyclopedia 】

  1. MetadataforData that describes data, mainly describes the data attribute information, used to support such as indicating storage location, historical data, resource search, file records and other functions.
  2. The greatest benefit of metadata is that it enables the description and classification of information to be formatted, thus making it possible for machine processing.

For more, see this blog post: MetaData.

4.2.2.2. Preparation

Allocates memory for class variables and sets default initial values for the class variables. The zero value. There is the following code:

	class Test{
		public static int a = 1;
	}
Copy the code

In the preparation phase, the class variable A at this point simply has a value of 0, not 1.

  1. This does not include static variables decorated by final, because final allocates a fixed value at compile time, which puts the result into the constant pool. It is initialized at run time and can be assigned to this fixed value directly. The value cannot be modified after assignment, but the constant pool can only refer to the basic data type +String.
  2. There are no initializations assigned to instance variables. Because class variables are allocated in the method area, instance variables are objects and are allocated in the Java area just like any other object. This is not to say that a class variable is not an object, but that a class variable is itself a special kind of object. It is allocated in the method area, not in the heap like all new objects.

In fact,Preparation stageThe operation can be simply interpreted as: build only the simplest class, unless we have written final staitc and are (8+1) base data types, assign the default value of zero, and the reference type is null.

4.2.2.3. Parsing phase
  1. Converts symbolic references in a constant pool to direct references.
  2. A symbolic reference is a set of symbols that describe the object being referenced. The literal form of a symbolic reference is clearly defined in the Java Virtual Machine Specification’s Class file format. A direct reference refers directly to a targetPointer to the,Relative offsetOr one that indirectly locates the targethandle.
  3. The parse action mainly applies to classes or interfaces, fields, class methods, interface types, and method types, which correspond to CONSTANT_Class_info, CONSTANT_Fieldref_info, and CONSTANT_Methodref_info in the constant pool.

4.2.3. Initialization phase

As the second big stage, the link stage only completes the loading of the class and the initialization of the data type. Except for some constant values, other class objects and instance objects are not correctly assigned. The third phase, initialization, is to complete the remaining problems.

  1. The initialization phase executes the class constructor methodThe < Clinit > () methodNotice that the constructor method is different from the constructor method.
  2. The instructions in the constructor method execute in the order in which the statements appear in the source file.
  3. The < Clinit > () methodDifferent from class constructors: The constructor is from the virtual machine perspective<init>().
  4. If the class already has a parent, then subclasses are guaranteedThe < Clinit > () methodBefore execution, the parent classThe < Clinit > () methodStatement execution is complete.
  5. The virtual machine must guarantee a classThe < Clinit > () methodIn the case of multithreadingSynchronous lockingThe initialization of a static block of a class can be performed only once.This is an important theoretical basis for our static inner classes to implement thread-safe lazy singletons.
  1. The singleton pattern

Divided into hungry and lazy, hungry type born thread safety, but can not do lazy loading. The slacker approach is thread-safe, but requires locking, otherwise multiple threads may create different instances. At present, several thread-safe lazy singleton methods have a common locking process. The nature of a static inner class makes it natural to implement the lazy singleton pattern. The first is thread-safety. In 3.5 above, we learned that the initialization of a static block of code in a class is locked by the JVM, so we don’t need to manually lock it. The second is lazy loading. The classloader will load the static inner class for us only when we call it, otherwise it will not load it. In this way, we implement the thread-safe lazy singleton pattern.

2. Constructors, constructors,

instance constructor, and

() class constructor

  1. The constructorConstructor: also called constructor. This is the constructor of a new class in the code we write.
  2. The constructor: A Javac compilation that generates a function that is a “function” that exists at the bytecode level. It’s actually useful for some codePost-integration generationThe function.
  3. <init> Instance constructor: for instance construction.
  4. ,<Clinit>() class constructor: Cinit is for classes.

There is at least one

instance constructor and only one

() class constructor. This is because only one class object can exist in JVM memory (with the same classloader). 3. Enumeration classes. An enumerated Class is a special Class whose underlying Class is essentially a Class, except that it is a member variable (called by the Class name) that is modified by public static final, so it is initialized together ina static block. Since the loading and initialization processes of Java classes are thread-safe, creating an enum type is thread-safe, so it is possible to implement a thread-safe singleton with an enumerated class.

4.3 Changing process of static instance variable assignment:

#### code 1:

	pivate static int number = 1;
Copy the code
The serial number phase value
1 Loading stage
2 Link-validation
3 Link – Prepare 0
4 Link – parse 0
5 Initialization phase 10

Code 2:

	private final static int number = 10;
Copy the code
The serial number phase value
1 Loading stage
2 Link-validation
3 Link – Prepare 10
4 Link – parse 10
5 Initialization phase 10

Note that the implementations of the various virtual machines are different, for example the HotSpot virtual machine is assigned initial values during the validation-prepare phase, whereas the JVM specification is assigned initial values during the initialization phase. See source 1 for details

Code 3:

private int number = 10;
Copy the code

The initial value is assigned when the specific instance is created.

Earlier, we looked at the different stages in which a Class is loaded into the JVM, but it is our Class Loader that performs the loading process.

Class loaders are divided into three types:

  1. BootStrap ClassLoader: This is a class shelf written in C/C++ and nested within the JVM. To load Java’s core class librariesJar file in the JAVA_HOME/jre/lib/rt.jar, resources.jar, or sun.boot.class.path directory.
  1. BootStrapClassLoaderThere is no parent loader, but it is the parent of the extension classloader.
  2. BootStrapClassLoaderOnly package names can be loadedJava, Javax, sunThe class at the beginning.
  1. Extension Classloader
    • I. Extension classloader: Written in the Java language and derived from BootStrapClassLoader. Load the class library from the directory specified by the java.ext.dirs system properties, or from the JRE /lib/ext subdirectory (or extension directory) of the JDK installation directory. If the JAR created by the user is placed in this directory, it will also be loaded by the extension classloader.

    • Ii. Application class loader (system class loader) : Written in the Java language and derived from the BootStrapClassLoader, it is responsible for loading the class libraries in the path specified by the environment variable classpath or the system property java.class.path. This class is the default classloader. In general, it loads classes for Java applications.

    • Iii. User-defined class loaders.

6. Parent delegation

Explain a lot about parents delegate mechanism on the Internet, in layman’s terms, delegate mechanism is when the class loading, we will give the task “contracted” class loaders, however class loader will not to class is loaded, but prior to its parent class to load, if the parent class can be loaded, so I won’t load, USES data from the parent class loading.

The purpose of this is to protect the source of class loading, to prevent duplication of class loading and malicious tampering of the core API resulting in code leakage or functionality loss.

7. Active and passive use

The JVM must know whether a type is loaded by the BootStrap ClassLoader or another ClassLoader.

If a type is loaded by a user classloader, then the JVM stores a reference to that classloader in the method area as part of the type information. When a reference from one type to another is resolved, the JVM needs to ensure that the classloaders for both types are the same.

JVM use of classes is divided into active use and passive use. Among them, active use is subdivided into seven cases:

  1. Create an instance of the class

  2. Access a static variable of a class or interface, or assign a value to that static variable.

  3. Call the static methods of the class

  4. reflection

  5. Initializes a subclass of a class

  6. The class that is identified as the startup class when the Java virtual machine is started

  7. JDK7 began to provide dynamic language support Java. Lang, invoke. MethodHandle instance analytic results REF_getStatic, REF_putStatic, REF_invokeStatic handle the corresponding class does not initialize the initialization.

Except for the above seven cases, all calls are considered passive calls to the class and do not result in class initialization.

If the same class is loaded by different class loaders, then the two classes are different classes.

8. To summarize

The.class file is read into the JVM’s method area by the classloading subsystem, where the most basic Class information is stored. The phases of the classloading subsystem’s operation assign values to our classes, call static methods, and so on. The red line in the figure is the main process of class loading.

Reference source
  1. A Deep Understanding of the Java Virtual Machine-Jvm Advanced Features and Best Practices. By Zhiming Zhou
  2. Do you know when final and static modifiers are assigned in Java?
  3. How are Java enumerated classes initialized, and why are enumerated classes thread-safe
Further reading
  1. Hot Replacement of Java classes — Concept, design, and implementation