preface

JVM partial theory, please adhere to. Some related tools are: jConsole, jVisualVm. exe, jmap, JPS, jStack, directly in the console can be used.

The JVM is?

  • It’s not so much that Java is a very good language and well designed, but that the PLATFORM for the JVM is well designed.
  • Not only does it support excellent languages like Java, but it also supports other languages like Kotlin and Scala.
  • That is, Java and the JVM are not tightly bound.
  • That is, it’s not a language that runs on the JVM, it’s a class file, or bytecode file, that can run on the JVM from any language that can be translated into bytecode that the JVM can read and run.
  • HotSpot is a SUN JVM implementation, as well as some commercial JVM implementations.
  • The JVM has specifications, and you can implement your own JVM just by following those specifications.

ClassLoading

In Java code, type loading, concatenation, and initialization are all done at runtime

  • Types: are classes, interfaces, enumerations, etc., defined when we write code, called types. Not an object!!

    • Type loading is done at Runtime. Put together an organic assembly of runtime types.
    • Java is a static language, but it has some of the characteristics of a dynamic language.
    • Instead of loading all classes at once and then running them, it ensures that the base classes (like the base classes) that the program runs on are fully loaded into the JVM, and that the rest of the classes are loaded as needed.
    • Java’s reflection mechanism, for example, is dynamic.
  • Classes are typically loaded in three stages: type loading, concatenation, and initialization.

  • Typical type loading is to load a class file from disk into memory. (Not the only way)

  • Concatenation: There are a lot of steps, in simple terms, to determine the relationship between classes, bytecode verification and so on, as well as class to class call relationship, such as symbolic reference to direct reference, etc., in this phase.

    What’s wrong with bytecode, you might say, as long as the Java code is right, how can bytecode be wrong? Normally it won’t, but if I manually open the class file and modify the contents, it might make an error, so it needs to be checked.

  • Initialization: Assigns a value to a static variable in a class.

Instead of strictly following the above three steps, it is possible to connect during a type load, and there are some differences between JVM implementations.

ClassLoader

Class loader is a tool that loads types into JVM memory. All types that want to enter JVM memory go through the class loader.

JVM and program life cycle

The Life cycle of a Java virtual machine ends in one of the following situations

  • After the system.exit () method is executed, the program completes normally.
  • The program was encountered during executionException or errorAbnormal termination.
    • If you write code without a catch exception, the exception is passed to the main method, causing the JVM and the program to terminate.
  • The Java virtual machine process was terminated due to an operating system error. Procedure
    • It’s force majeure.

Load, connect, initialize, use, and unload classes

Class loading

  • Find and load the binary data for the class

The connection

  • Validation: To ensure the correctness of the classes being loaded.
  • Prepare: for classStatic variables allocate memoryAnd initialize it toThe default value. (int 0,boolean false)
       public static int a = 1;// INSTEAD of a being equal to 1, a is given a default value of 0.
    Copy the code
  • Parsing: Converts symbolic references in a class to direct references.
       a = classA;
       c = a;//c refers to the symbol a, which refers directly to classA when parsed. I don't care what A is.
    Copy the code

Initialize the

  • Assigns the correct values to static variables of the classThe initial value.
      public static int a = 1;// The default value 0 assigned during the connection phase will be correctly assigned to the initial value 1
    Copy the code

use

  • For example, create an object from a class.
  • Invoke the relevant methods of the class.
  • , etc.

uninstall

  • Remove the classes from memory, and no more objects can be created.

further

Class loading

Is the class loaded?

  • Loading a class means reading the binary data from the class’s.class file into memory, placing it in the method area (meta space) of the runtime data area, and then creating a java.lang. class object in memory. (The specification doesn’t say where the class object is located, The HotSpot VIRTUAL machine places it in the method area) to encapsulate the data structure of the class in the method area.
  • No matter how many instances are generated, there is only one final Class object.
  • Class objects are like mirrors that reveal all the content and structure of a Class, which is the source of reflection.

How is the class loaded?

  • Load directly from the local system.
  • Download the. Class file from the network.
  • Load. Class files from zip, JAR, etc archives.
  • Extract. Class files from a proprietary database.
  • Dynamically compile Java source files into.class files.
    • Like dynamic proxy
    • For example, when you run a JSP, the JSP is translated into a servlet that further becomes a.class

Initialize the

Before WE get to that, how do Java programs use classes?

  • Use it actively.
  • Passive use.

When does initialization occur?

  • All Java virtual machine implementations must initialize each class or interface when it is “first actively used” by a Java program.
  • In other words, classes are not initialized when used passively.

What does active use mean?

  • Create an instance of the class.
    new Thread();
    Copy the code
  • Accesses or assigns a value to a static variable of a class or interface.
    System.out.println(StaticClass.value);// Access static variables.
    StaticClass.value = "hello world";// Assign values to static variables.
    Copy the code
  • Call a static method of a class.
    StaticClass.function();
    Copy the code
  • reflection
    Class.forName("com.test.Test")
    Copy the code
  • Initialize a subclass of a class.
  • Classes that are identified as startup classes when the Java virtual machine starts
    • The class of the most common main method.
    • Unit testing, Junit, etc.
  • Dynamic language support starting with JDK1.7:
    • Java. Lang. Invoke. Analytical results REF_getStatic MethodHandle instance, REF_putStatic, REF_invokeStatic handle corresponding class does not initialize, is initialized. (Rare).

What does passive use mean?

  • In addition to the 7 kinds of active use mentioned above, the others are passive use.

Some code to illustrate class initialization

As we all know, static code blocks run automatically without new.

  • code
public class InitTest {
    public static void main(String[] args) { System.out.println(Child.str); }}//static represents Class
class Parent{
     public static String str = "hello world";
     static {
         System.out.println("Parent static block"); }}class Child extends Parent{
     static {
         System.out.println("Child static block"); }}Copy the code
  • The results of

  • You can see that the subclass’s static code block is not running.
    • You can see that the subclass does not meet the “first active use” condition; it is not initialized.
    • The parent class satisfies the “active use” condition of accessing static variables (STR is accessed in the main method).
    • It is further concluded that the static code block is executed after initialization in the class load.
  • For static fields, only the class that directly defines the field is initialized.

  • A little code change, access the subclass static variable, let the parent class initialize
public class InitTest {
    public static void main(String[] args) {
        System.out.println(Child.string);// Access the subclass static variable, causing the parent class to be initialized}}//static represents Class
class Parent{
     public static String str = "hello world";
     static {
         System.out.println("Parent static block"); }}class Child extends Parent{
    public static String string = "Welcome to China";
     static {
         System.out.println("Child static block"); }}Copy the code
  • The results of

  • When a class is initialized, all of its parents are required to have been initialized.

For a class that is not initialized, is it loaded?

  • As you can see from the first code example, this only results in the execution of a static code block when the class is initialized.
    • The static block of the Child class is not executed, so it is not initialized. How do we know if it is loaded?
  • You can use the JVM’s run parameters to get whether or not a class is loaded.
    • -xx :+TraceClassLoading Is used to trace and print the loading information of classes.

The VM options

  • The results

  • Learned that static code blocks are only executed when classes are initialized.
  • Classes are loaded even if they are not initialized.

About VM parameters

  • The form is fixed
-XX:+<option>// Enables the option option
-XX:-<option>// Disables the option option

/* There are also common arguments to resize JVM memory, which look like this: */
-XX:<option>=<value>// Sets the value of the option option to value
Copy the code