I did not resist the Java class loading mechanism of the

For a long time, I have very resistance to Java's class loading mechanism, because I think it is too difficult to understand. But in order to become a good Java engineer, I decided to bite the bullet and look.

01, bytecode

Before talking Java class loading mechanism, we need to understand Java byte code, and because it is closely related to class loading mechanism.

Computer known only 0 and 1, so any programming language are compiled into machine code needs to be understood by the computer, and then perform, Java is no exception.

Java at the time of the birth of a very fast hardware shouted the slogan: "Write Once, Run Anywhere", in order to achieve this goal, Sun has released a number that can run on different platforms (Windows, Linux) Java Virtual Machine (JVM ) - responsible for loading bytecode compilation and execution of Java.

Java bytecode in the end what it was like, we use a simple piece of code to look at.

Source as follows:

package com.cmower.java_demo;

public class Test {

    public static void main(String[] args) {
        System.out.println("沉默王二");
    }

}

After the code is compiled through, by xxd Test.classcommand look at the byte code file.

xxd Test.class
00000000: cafe babe 0000 0034 0022 0700 0201 0019  .......4."......
00000010: 636f 6d2f 636d 6f77 6572 2f6a 6176 615f  com/cmower/java_
00000020: 6465 6d6f 2f54 6573 7407 0004 0100 106a  demo/Test......j
00000030: 6176 612f 6c61 6e67 2f4f 626a 6563 7401  ava/lang/Object.
00000040: 0006 3c69 6e69 743e 0100 0328 2956 0100  ..<init>...()V..
00000050: 0443 6f64 650a 0003 0009 0c00 0500 0601  .Code...........
00000060: 000f 4c69 6e65 4e75 6d62 6572 5461 626c  ..LineNumberTabl

Feeling a bit ignorant force, right?

Ignorant on the right.

This bytecode cafe babeis called "magic number" is the identification flag JVM .class files. Customizer file format can be selected freely magic value (as long as not used), for example, .png file magic number is 8950 4e47.

As for the other content Well, you can choose forgotten.

02, class loading process

Learn the Java byte code, let's talk about Java's class loading process.

Java's class loading process can be divided into five stages: loading, validation, preparation, analytical and initialization. Five phases generally occur sequentially, in the case of dynamic binding, resolved phase occurs after the initialization phase.

1) Loading (loading)

JVM main purpose of this phase is different from a byte code of the data sources (could be the class file, it may be jar package, even network) converted to a binary stream of bytes loaded into memory, and generates a representative of the class java.lang.Classobject.

2) Verification (authentication)

JVM will be verified binary byte stream at this stage, only to meet the JVM bytecode JVM specification is correctly implemented. This stage is important to ensure the JVM security barrier, the following are some key checks.

  • Ensure binary byte stream format in line with expectations (for example, whether to cafe benebegin with).
  • Are all methods comply with access control defined keywords.
  • The number and type of parameters the method call is correct.
  • Ensure that the variable is initialized prior to use correctly.
  • Check if the variable is assigned the value of the right type.

3) Preparation (preparation)

The JVM class variables (also referred to as static variables, at this stage staticmodified keywords) allocate memory and initialize (default initial value corresponding data types, such as 0,0L, null, false, etc.).

In other words, if there is such a piece of code:

public String chenmo = "沉默";
public static String wanger = "王二";
public static final String cmower = "沉默王二";

chenmo not allocate memory, and wanger will; but the initial value wanger not "king" instead null.

It should be noted that the static finalmodified variables are known as constants, class variables and different. Once the constant assignment will not change, so cmower is in the preparation stage "silent king" instead null.

4) Resolution (resolved)

This phase reference symbol the constant pool into direct reference.

what? Symbolic references, direct reference?

Symbolic references to a set of symbol (literal in any form, as long as the unambiguous in use to locate the target) referenced to describe target.

At compile time, Java class does not know the actual address of the referenced class, you can only use symbolic references instead. For example, com.Wangerclass references com.Chenmoclasses, compile-time Wanger class does not know the actual memory address Chenmo class, so only use symbols com.Chenmo.

Direct reference to parse through symbolic references, find the actual memory address references.

5) Initialization (initialization)

This phase is the final step class loading process. During the preparation phase, class variables have been assigned through the default initial value, while in the initialization phase, the class variables will be assigned code expects the value of poetry. In other words, during the initialization phase is performed class constructor method.

oh, no, the above paragraph is all very abstract and difficult to understand, right, I give you an example.

String cmower = new String("沉默王二");

The code above uses newkeywords to instantiate a String object, then this time, it will call the constructor method of the String class to instantiate cmower.

03, the class loader

After talking with the class loading process, you have to talk to the class loader.

In general, Java programmers do not need to directly interact with the same loader. JVM's default behavior is enough to meet the needs of the majority of cases. However, if you encounter a situation and need to interact with the class loader, and the mechanism of class loaders are not very understanding, then you have to spend a lot of time to debug
ClassNotFoundExceptionand NoClassDefFoundErrorother abnormalities.

For any class, we need to identify its uniqueness by the JVM class loader and its class itself together. That is, if two different class loader, even if a two byte code class files from the same, and that this must not be equal to two classes (two classes such as Class object is not equals).

Standing on the programmer's perspective, Java class loader can be divided into three types.

1) Start class loader (Bootstrap Class-Loader), loading jre/libthe package following jar file, such as a common rt.jar.

2) extension class loader (Extension or Ext Class-Loader) , loading jre/lib/extthe package following jar file.

3) application class loader (Application or App Clas-Loader), a program based on the class path (CLASSPATH) to load Java classes.

Come learn about the next by a simple code.

public class Test {

    public static void main(String[] args) {
        ClassLoader loader = Test.class.getClassLoader();
        while (loader != null) {
            System.out.println(loader.toString());
            loader = loader.getParent();
        }
    }

}

Each Java class maintains a pointer to the class that defines it loader referenced by 类名.class.getClassLoader()this reference can be obtained; then loader.getParent()you can get the upper class loader class loader.

The output of this code are as follows:

sun.misc.Launcher$AppClassLoader@73d16e93
sun.misc.Launcher$ExtClassLoader@15db9742

The first output line of the Test class loader, i.e. application class loader, it is the sun.misc.Launcher$AppClassLoaderinstance of a class; second output line extension class loader, are sun.misc.Launcher$ExtClassLoaderinstances of classes. That class loader to start it?

It stands to reason, the upper class loader extension class loader is the class loader to start, but in my version of the JDK, the extension class loader getParent()returned null. So there is no output.

04, parent delegation model

If the above three types of loading can not meet the requirements, then, the programmer can also customize the class loader (inherited java.lang.ClassLoaderclass), the hierarchical relationship between them is shown below.

This hierarchy is referred to as a parent delegation model : If a class loader to load classes received a request, it will first request entrusted to the upper loader to complete, top loader will entrust the upper loader until most top class loader; if upper loader working class can not finish loading, the current class loader will try to load their own class.

PS: Parents delegation model suddenly reminds me of Comrade Zhu Yuanzhang, after the comrades became emperor even the prime minister are not, everything themselves, only they did not have time to do energy only to the ministers to get there.

Use parent delegation model has an obvious advantage, it is a Java class with its class loader has the priority level together with a relationship of, it is very important to ensure the stable operation of Java programs.

As mentioned above, if two different class loaders, two classes from the same even if a byte code file, and that the two classes will surely not equal - parent delegation model to ensure the same class will eventually be particular class loader loads.

05, finally

Bite the bullet and look at a lot of information, and hands to research, I found that he was on the Java class loading mechanism (JVM will be dynamically added to the class information and a mechanism for memory use) less resisted - really pretty wonderful thing ah.

也许学习就应该是这样,只要你敢于挑战自己,就能收获知识——就像山就在那里,只要你肯攀登,就能到达山顶。

 

Guess you like

Origin www.cnblogs.com/qing-gee/p/11163201.html