A deep understanding of the class loading mechanism of Java virtual machines and a deep understanding of virtual machines

Source: Internet
Author: User
Tags array definition

A deep understanding of the class loading mechanism of Java virtual machines and a deep understanding of virtual machines
1. class loading time

For the first phase of class loading-loading, the virtual machine has no mandatory constraints,For the initialization phase, Virtual machine mandatory provisionYes and onlyIn the following 5 cases, initialization must begin. Of course, the loading, verification, and preparation phases have started before initialization.

① UseNew Keyword instantiation objectWhen, when reading or setting static fields of A Class (except static fields modified by final), and when calling static methods of a class.

② Perform classReflectionWhen calling

③ If a class is initializedThe parent class has not been initialized., You must first trigger the initialization of the parent class.

④ When a virtual machine is started, you must specifyMain class(The class that contains the main () method). The virtual opportunity first initializes the main class.

⑤ When JDK 1.7 is used for dynamic language support, if a method handle of the final parsing result REF_getStatic, REF_putStatic, and REF_invokeStatic of a java. lang. invoke. MethodHandle instance is usedThe class corresponding to the method handle has not been initialized., You must first trigger its initialization.

The behavior in the above five scenarios is calledActive reference. For other references, virtual machines do not trigger class initialization.Passive reference.

  Example of passive reference:

/** Reference the static fields of the parent class through the subclass. This does not cause the subclass to initialize **/public class SuperClass {static {System. out. println ("SuperClass init! ");} Public static int value = 123;} public class SubClass extends SuperClass {static {System. out. println (" SubClass init! ");}}
/*** Demo of non-active use of class fields **/public class NotInitialization {public static void main (String [] args) {System. out. println (SubClass. value );}}

Result: Only SuperClass init is output!

/*** Passive Use of class field demonstration 2: * Reference a class through array definition, initialization of this class will not be triggered **/public class NotInitialization {public static void main (String [] args) {SuperClass [] sca = new SuperClass [10];}

Result: No SuperClass init is output!

/*** Demo of non-active use of class fields **/public class NotInitialization {public static void main (String [] args) {System. out. println (ConstClass. HELLOWORLD );}}

Result: "ConstClass init!" is not output !"

Interface loading process: it is only different from the third entry in the class loading process. When a class is initialized, it requires that all its parent classes have been initialized. However, when an interface is initialized, the parent interface is not required to complete initialization. Initialization is only performed when the parent interface is actually used (for example, a constant defined in the reference interface.

2. class loading process 2.1:

In the loading phase, the virtual machine must complete three tasks:

① Get the binary byte stream defining this class through the full qualified name of a class.

② Convert the static storage structure represented by this byte stream into the runtime data structure of the method area.

③ Generate a java. lang. Class Object that represents this Class in the memory, and serve as the access portal for various data of this Class in the method area.

2.2 connection: 2.2.1 Verification:

      The purpose of the verification phase is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine and does not endanger the security of the virtual machine itself.. Virtual machines mainly do the following:

① File format verification: for example, starting with the magic number 0xCAFEBABE

② Metadata verification: for example, whether a parent class exists

③ Bytecode verification: Method body verification for the class

④ Symbol reference verification: for example, whether the corresponding class can be found by fully qualified names

2.2.2 preparation:

The preparation phase is the phase in which the memory is officially allocated to the class variables and the initial values of the class variables are set. The memory used by these variables will be allocated in the method area.For example:

Public static int values = 123;

      Preparation PhaseOnly the initial value (that is, 0) of the class variable is assigned to the value.Initialization phaseAssign 123 to value.

      Note:If it is a final modified string, the virtual opportunity initializes the variable in the preparation phase. As follows:

Public static final int value = 123;

During compilation, Javac will generate the ConstantValue attribute for the value. during the preparation phase, the virtual machine will assign the value to 123 according to the ConstantValue settings.

2.2.3 Resolution:

      The parsing phase is the process in which the Virtual Machine replaces the symbol reference in the constant pool with the direct reference.It mainly resolves class or interface, field, class method, interface method, method type, method handle, and call point qualifier 7 Class symbol reference.

2.3 initialization:

All actions before this areDominated by virtual machinesThe Java code defined in the class is executed only in the initialization phase. That is, fromProgrammerCode written to initialize class variables or other resources can be executed only in the initialization phase.

In fact, the initialization process is the process of executing the <clinit> () method of the class constructor, <clinit> () the method is generated by the compiler automatically collecting the values of all class variables in the class and merging the statements in the static statement block (static, the sequence collected by the compiler is determined by the order in which the statements appear in the source file.

      The static statement block can only access the variables defined before the static statement block and the variables defined after it. The previous static statement block can be assigned values, but cannot be accessed.The following code:

// Invalid forward reference variable: public class Test {static {I = 0; // assign a value to the variable. The variable can be compiled through System normally. out. print (I); // the compiler will prompt "illegal forward reference"} static int I = 1 ;}
3. class loaders: 3.1 Class and Class loaders:

Get the binary byte stream Class Loader describing this class by using a fully qualified class name (such as reflection). The Code module of this action is called the class loader.

   Determine whether two classes are equal:

① Whether the class name is the same, including the package name;

② Whether it is loaded by the same class loader makes sense only when two classes are loaded by the same class loader. Otherwise, even if both classes are from the same class file, the class loaders for loading this class file are different, so these two classes are not equal.

The VM provides three types of loaders: Bootstrap class loader, Extension class loader, and System class loader (also called Application Class Loader ).

   Start the Class Loader:<JAVA_HOME>/jar packages in the path specified by the core class library or the-Xbootclasspath In the lib path. For security reasons, only classes whose names start with java, javax, and sun are loaded.

   Extension Class Loader:Load the class library in the <JAVA_HOME>/lib/ext directory or by the system variable-Djava. ext. dir

   Application Class Loader:It is also called the system class loader. Load the class library in the path specified by the system class path java-classpath or-D java. class. path, that is, the classpath path we often use. developers can directly use the system class loader.

3.2 Parental appointment mode:

When the class loader loads a class, it first delegates its parent class loader to load the class. Similarly, the parent class loader also delegates its parent class loader to load the class, until the top-level start class loader, the start class loader does not have a parent class by default. When the start class loader cannot load this class, it delegates it to its subclass loader, similarly, delegate until a subclass loader can load the class successfully. Otherwise, an error is returned. This is the two-parent delegation mode.

Advantages of using the parental delegation mode:

① Avoid repeated class loading: when the parent class has already loaded this class, the subclass does not need to be loaded again.

② Prevent the core api library from being tampered with: When a java is transmitted from the network. lang. when the Object class is used, the Class Loader delegates to the start class loader in the parent-parent delegation mode. The start class loader finds that the class has been loaded and will not load the passed class, instead, it directly returns the loaded class.

Destroys the Parent-Child delegation mode:

    ① UseThread context Class LoaderWhen the base class is called back to the user's code, because of the existence of the parent-child delegation mode, the Class Loader cannot be started to delegate to the sub-class loader to load the class, in this case, the thread context loader is used to solve the problem. Common examples include JNDI, JDBC, JCE, JAXB, and JBI.

    Take jdbc as an example:<JAVA_HOME>/lib has encapsulated jdbc interfaces. Different database vendors compile implementation classes for these interfaces according to interface specifications, however, these Implementation classes are usually placed in the classpath path. The class loader needs to call the implementation classes of these interfaces, but it cannot load classes in the classpath path, classes in the classpath path can only be loaded by the system class loader. Due to the existence of the parent class delegation mode, the subclass loader can only delegate the parent class loader to load classes, the parent class loader cannot delegate the class to the sub-class loader. So there is a compromise. When the class loader needs to call the implementation classes of these interfaces, it entrusts the thread context class loader to load these Implementation classes. By default, the thread context class loader is the system class loader.

Code Hot replacement (HotSwap) and module Hot Deployment (Hot Deployment ):

    This means that the application can be connected to the mouse and USB flash drive as the computer peripherals do. You can use the application immediately without restarting the machine. If you have any mouse problems or want to upgrade the application, change the mouse, no downtime or restart. The specific application example is the automatic release of a project under Tomcat. After the jsp is modified, the server does not need to be restarted.

4. Tomcat analysis:

Common Class Loader:LoadLibClass files under the Directory

Webapp Class Loader:Load/WebApp/WEB-INF /*Class File

Jsp Class Loader:Its loading scope is only the Class compiled by the JSP file. It appears to be discarded: when the server detects that the JSP file has been modified, the current JasperLoader instance is replaced, and a new Jsp class loader is created to implement the HotSwap function of the JSP file.

WebApp classloaders and Jsp classloaders usually have multiple instances. Each Web application corresponds to a WebApp classloader, and each JSP file corresponds to a Jsp classloader.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.