JVM (7): VM class loading mechanism

First, the class loading timing

....pending upgrade

Second, the class (Class) loading

Non-array type loading phase:

After the Class to run and use the file needs to be loaded into the virtual machine, the virtual machine how to load the Class?

Load Class file type is mainly three steps: Load -> Connection ( connected three-step process: Verify -> Prepare -> parse) -> initialization ;

Therefore, the specific class loading process has five steps: loading, verification, preparation, parsing initialization

Array class loader type:

         Not created by a class loader, which created directly by the JVM 

2.1, load

Loaded mainly to complete the following three things:

  1. Such definition acquired by the full class name of a binary byte stream ;
  2. Converting the byte stream static storage structure represented by the area method of run-time data structure ;
  3. Generating in memory representative of a class of Class objects , as a method of access to the entrance area of such data.

Note : array type is not created by class loaders, but created directly by JVM

Note : loading phase and the connection phase cross, not the end of the load connection may have started

2.2, verify

As a first step the connection phase. The purpose is to ensure that the information contained in the Class file byte stream meets the requirements of the current virtual machine and the virtual machine will not jeopardize safety.

Verify performs the following four things:

(1) file format validation

Verify whether the Class byte stream file format specifications , and can be understood by the current virtual machine

(2) metadata validation

Bytecode information described semantic analysis, to ensure compliance with the information which describes the Java language specification requirements

(3) bytecode verification

The data flow and control flow analysis to determine the semantics of the program is legitimate, logical. Method body of the Java class detail check

(4) Symbol reference check

It will take place in the virtual machine into a symbolic reference when directly referenced. Is a class other than its own checksum (various symbols are constant pool reference)

2.3, ready

The second step as the connection phase. The aim of class variables allocate memory and set the initial value for class variables , these memory in the method area allocation

Note :

(1) In this case the memory allocation includes only class variables (static variables) , and does not include the instance variables. Instance variables and instance when the object is an object with only the Java heap memory allocation;

(2) the initial value set here, generally refers to data type Default value 0 (e.g., 0,0L, null, false, etc.).

2.4, parsing

The second step as the connection phase. Object is a virtual machine to a symbolic constant pool references cited direct replacement process (i.e. to give classes, methods, fields in memory pointer or offset) .

JVM for each class prepared a method table , when you need to call the method of this class, just know that this method Offset (address) in the method of the table you can call this method directly. By parsing operation symbolic references can be converted directly to the reference position to locate the target method in the class, so that the method may be invoked.

(7 symbol class action: class or interface, fields, methods class, interface method, type method, a method handler, call qualifier)

2.5, initialization

Classloading last step. Object is actually executed in Java code executed class constructor method <clinit> () procedure .

JVM provides that only five cases must be initialized categories:

(1) when encountering new, GetStatic, putstatic, invokestatic when this instruction code directly 4; such a new class, reads a static field (not final modification), a static method call class;

(2) using the  java.lang.reflect packet-based methods for reflection to invoke the time;

(3) initialize a class if not the parent class is initialized to trigger the initialization of the parent ;

(4) virtual machine starts, the user needs to define a group containing the main method of the main class, a virtual machine to initialize the main category;

(5) slightly

 

Third, the class loader

3.1, introduced three types loader

JVM built three ClassLoader, in addition to the other two BootstrapClassLoader by Java implementation and inheritance java.lang.ClassLoader

(1) BootstrapClassLoader ( boot class loader ):

Topmost loader implemented ++ C , responsible for loading the  %JAVA_HOME%/libjar and the package directory or class or  -Xbootclasspathall classes of parameters specified path;

(2) ExtensionClassLoade R & lt (extended class loader)  :

Primarily responsible for loading the directory  %JRE_HOME%/lib/ext jar package and class directory, or  java.ext.dirs jar package under system variables path specified;

(3) AppClassLoader (application class loader):

User-oriented loader is responsible for loading the current class and all the jar packages under application classpath.

 

3.2, parent delegation model

Parent delegation model description :

Each class has a corresponding class loader, the system will use the default class loader delegation model parents: that when loaded will first determine whether the class is over-loaded, loaded class will be directly returned, otherwise it tries to load; load time will the delegates to the class of the parent class loader loadClass() process (so that all your request will be passed to the top of the boot class loader BootstrapClassLoader process (so called parents) ), when the parent class loader We will deal with their own time to process.

Note :

(1) Each class has a parent class loader;

(2) when the parent class loader is null, it does not mean that no parent class loader, and the description of the parent class loader BootstrapClassLoader;

Parent delegation model benefits :

(1) to ensure stable running Java programs can avoid repeated load class;

 

Parents do not want to delegate model we supposed to?

You can customize the loader, inherited from java.lang.ClassLoader,overwriting loadClass () method

Parent delegation model to achieve source code analysis:

In  java.lang.ClassLoader the  loadClass() middle, the relevant code is as follows:

private final ClassLoader parent; 
protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            // 首先,检查请求的类是否已经被加载过
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    if (parent != null) {//父加载器不为空,调用父加载器loadClass()方法处理
                        c = parent.loadClass(name, false);
                    } else {//父加载器为空,使用启动类加载器 BootstrapClassLoader 加载
                        c = findBootstrapClassOrNull(name);
                    }
                } catch (ClassNotFoundException e) {
                   //抛出异常说明父类加载器无法完成加载请求
                }
                
                if (c == null) {
                    long t1 = System.nanoTime();
                    //自己尝试加载
                    c = findClass(name);

                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }

### If you have help, welcome thumbs up! comment! Forwarding! Thank you!

Previous: Class File Structure

  Reference: in-depth understanding of the Java Virtual Machine (Version 2): JVM advanced features and best practices

  Reference: "real Java Virtual Machine"

发布了52 篇原创文章 · 获赞 116 · 访问量 5万+

Guess you like

Origin blog.csdn.net/RuiKe1400360107/article/details/103534630