Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the timing and process of loading the Java class

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the loading time and process of Java class". Interested friends may wish to take a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the loading time and process of Java class"?

1 come straight to the point

I once saw an interview question for java. At that time, I thought it was very simple, but I ran the code by myself, but the result was not what I thought. The topics are as follows:

Class SingleTon {private static SingleTon singleTon = new SingleTon (); public static int count1; public static int count2 = 0; private SingleTon () {count1++; count2++;} public static SingleTon getInstance () {return singleTon;}} public class Test {public static void main (String [] args) {SingleTon singleTon = SingleTon.getInstance (); System.out.println ("count1=" + singleTon.count1) System.out.println ("count2=" + singleTon.count2);}}

Wrong answer

Count1=1

Count2=1

Correct answer

Count1=1

Count2=0

For what? For what? This starts with the class loading timing of java.

Type 2 loading timing

The entire life cycle of a class from being loaded into virtual machine memory until it is unloaded out of memory includes seven phases: loading, verification, preparation, parsing, initialization, use, and unloading. Among them, the three parts of verification, preparation and parsing are collectively called linking.

Among them, the order of the five stages of loading, verification, preparation, initialization and unloading is determined, and the loading process of the class must be a step-by-step "start" (only refers to the start, not the execution or end). Because these phases are usually mixed with each other, they are usually called or activated during the execution of one phase. The parsing phase is not necessarily (it can in some cases start after the initialization phase to support the runtime binding of the Java language.

3 when to start the initialization of the class

When you need to start the first phase of the class loading process: load. There is no forced constraint in the virtual machine specification, which can be freely controlled by the specific implementation of the virtual machine, but the virtual machine specification in the initialization phase strictly stipulates the following cases, if the class is not initialized, the class will be initialized.

Create an instance of the class

Access to static variables of a class (except constants [static variables by final rhetoric] reason: constants are special variables because the compiler treats them as value rather than field. If a constant (constant variable) is used in your code, the compiler does not generate bytecode to load the value of the field from the object, but inserts the value directly into the bytecode. This is a useful optimization, but if you need to change the value of the finalfield, then every piece of code that uses that field needs to be recompiled.

Access the static method of the class

Reflections such as (Class.forName ("my.xyz.Test"))

When initializing a class, it is found that the parent class has not been initialized yet, then initialize the parent class first

When the virtual machine starts, the class that defines the main () method initializes first

The above situation is called "active reference" to a class, except in this case, it does not trigger the initialization of the class, which is called "passive reference".

The loading process of an interface is slightly different from that of a class. Static {} blocks cannot be used in the interface. When an interface is initialized, all of its parent interfaces are not required to be initialized, but only when the parent interface is actually used (such as referencing constants defined in the interface).

4 examples of passive citation

The subclass calls the static variable of the parent class, and the subclass is not initialized. Only the parent class is initialized. For static fields, only the class that defines the field directly will be initialized.

Referencing a class through an array definition does not trigger the initialization of the class

Accesses the constant of the class and does not initialize the class

Class SuperClass {static {System.out.println ("superclass init");} public static int value = 123;} class SubClass extends SuperClass {static {System.out.println ("subclass init");}} public class Test {public static void main (String [] args) {System.out.println (SubClass.value); / / passive application 1 SubClass [] sca = new SubClass [10]; / passive reference 2}}

Program running output

Superclass init

one hundred and twenty three

From the input results above, passive reference 1 and passive reference 2 are proved.

Class ConstClass {static {System.out.println ("ConstClass init");} public static final String HELLOWORLD = "hello world";} public class Test {public static void main (String [] args) {System.out.println (ConstClass.HELLOWORLD); / / call class constant}}

Program output result

Hello world

From the output above, it is proved that passive reference 3

5 types of loading process 5.1 loading

The Loading phase is the first stage of the Class Loading process, in which the virtual machine needs to do the following three things:

1. Get the binary byte stream that defines this class through the fully qualified name of a class.

2. Transform the static storage structure represented by this byte stream into the run-time data structure of the method area.

3. Generate a java.lang.Class object representing this class in the Java heap as the access entry for the data in the method area.

The loading phase can be completed either by using the system-provided class loader or by the user-defined class loader. Some of the contents of the load phase and the connection phase (such as part of the bytecode file format verification action) are crossed, the load phase has not yet been completed, and the connection phase may have begun.

5.2 Verification

Authentication is the first step in the connection phase, which 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 compromise the security of the virtual machine itself.

The Java language itself is a relatively safe language, and it is impossible to use Java coding, such as accessing data outside the boundaries of the array, transforming an object to a type it does not implement, and so on. If you do, the compiler will refuse to compile. However, Class files are not necessarily compiled from Java source code, and can be written directly in any way, including using a hexadecimal editor such as UltraEdit. If harmful "code" (byte stream) is written directly, and the virtual machine does not check when loading the Class, it is possible to compromise the security of the virtual machine or program.

The implementation of class verification may vary from virtual machine to virtual machine, but it roughly completes the following four stages: file format verification, metadata verification, bytecode verification and symbol reference verification.

1. File format verification is to verify whether the byte stream conforms to the specification of Class file format and can be processed by the current version of the virtual machine. Such as verifying whether the magic number is 0xCAFEBABE, whether the major and minor version numbers are within the processing range of the current virtual machine, and whether there are any unsupported constant types in the constants of the constant pool. The main purpose of this verification phase is to ensure that the input byte stream can be correctly parsed and stored in the method area. After verification at this stage, the byte stream will be stored in the method area of memory. So the next three verification phases are all based on the storage structure of the method area.

2. Metadata verification is the semantic analysis of the information described by bytecode to ensure that the described information conforms to the requirements of Java language specification. It may include verification such as whether this class has a parent class, whether the parent class of this class inherits a class that is not allowed to be inherited, and if the class is not an abstract class, whether it implements all the methods required in its parent class or interface.

3. Bytecode verification, the main work is to analyze the data flow and control flow to ensure that the methods of the checked class will not endanger the security of the virtual machine at run time. There must be a problem if the bytecode of a method-like body fails bytecode verification, but if a method body passes bytecode verification, it does not necessarily mean that it is secure.

4. Symbol reference verification occurs when the virtual machine converts a symbol reference to a direct reference, and this conversion action will occur in the "parsing phase". Verify whether the corresponding class can be found by the permission name described by the string in the symbolic reference; whether there are descriptors in the specified class that match the method field and the methods and fields described by the simple name; whether the accessibility (private, protected, public, default) of the class, field and method in the symbolic reference can be accessed by the current class

The validation phase is not necessarily a necessary phase for the virtual machine's class loading mechanism. If all the code running is confirmed to be safe, you can use the-Xverify:none parameter to turn off most of the class validation measures to reduce the virtual machine class loading time.

5.3 preparation

The preparation phase allocates memory for static variables of the class and initializes it to default values, all of which will be allocated in the method area. The preparation phase does not allocate memory for instance variables in the class, which will be allocated in the Java heap along with the object when the object is instantiated.

The initial value of value for public static int value=123;// is 0 in the preparation phase. It will only become 123 in the initialization phase.

5.4 parsing

The parsing phase is the process by which the virtual machine replaces symbolic references in the constant pool with direct references.

Symbolic reference (Symbolic Reference): a symbolic reference uses a set of symbols to describe the referenced target. The symbol can be any form of literal quantity, as long as it can be used to locate the target without ambiguity. Symbolic references are independent of the memory layout implemented by the virtual machine, and the target of the reference is not necessarily loaded into memory.

Direct reference (Direct Reference): a direct reference can be a pointer to a target, a relative offset, or a handle that can be located indirectly to the target. Direct references are related to the memory layout implemented by the virtual machine, and if there is a direct reference, the target of the reference must already exist in memory.

5.5 initialization

Class initialization is the last step of the class loading process. In the previous class loading process, except that the user application can participate through the custom class loader in the loading phase, the rest of the actions are completely dominated and controlled by the virtual machine. It is not until the initialization phase that the execution of the Java program code defined in the class actually begins.

The initialization phase is the process of executing the class constructor () method. The () method is generated by the compiler automatically collecting the assignment actions of all class variables in the class and the statements in the static statement block (static {} block).

6 topic analysis above introduces the loading time and process of the class in detail, and analyzes the title of this article through the above theory.

Class SingleTon {private static SingleTon singleTon = new SingleTon (); public static int count1; public static int count2 = 0; private SingleTon () {count1++; count2++;} public static SingleTon getInstance () {return singleTon;}} public class Test {public static void main (String [] args) {SingleTon singleTon = SingleTon.getInstance (); System.out.println ("count1=" + singleTon.count1) System.out.println ("count2=" + singleTon.count2);}}

Analysis:

1:SingleTon singleTon = SingleTon.getInstance (); the SingleTon that called the class calls the static method of the class, triggering the initialization of the class

2: allocate memory for static variables of the class and initialize the default value singleton=null count1=0,count2=0 during the preparation process when the class is loaded

3: class initialization, fast assignment of static variables to the class and execution of static code. Singleton assigns to the constructor of the new SingleTon () calling class

4: count=1;count2=1 after calling the constructor of the class

5: continue to assign values to count1 and count2. In this case, count1 has no assignment operation, and all count1 is 1, but the assignment operation performed by count2 becomes 0 appendix:

At this point, I believe that everyone on the "Java class loading time and process is what" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report