In-depth understanding of the execution mechanism of Jvm_java Code 01

Source: Internet
Author: User

This chapter focuses on: 1, jvm:      How to compile Java code into a class file.       How to load class files and how to execute class files.     &NBSP;JVM How to allocate and recycle memory.     &NBSP;JVM Multithreading: The mechanism of thread resource synchronization and interaction between threads.  3.1 Java Code Execution mechanism  java the source code compilation mechanism.  1, three steps:          analysis and input to symbol table (parse and enter)               The  parse process is done for lexical and syntactic analysis.                      The lexical analysis: convert code strings to token sequences.                      parsing: Generates an abstract syntax tree from the token sequence according to the syntax.                enter process for entering into symbol table will conform well.                     It typically involves determining the superclass and interface of a class, adding a default constructor as needed, and having a symbol table for the symbol input class that appears in the class to be medium.           annotation processing (Annotation processing)                 main use User-defined annotation.           Semantic analysis and generation of class files (analyse and Generate)     &NBSp          analyse A series of semantic analyses based on the abstract syntax tree.                 includes     The names, expressions, and other elements of the syntax tree are associated with variables, methods, types, and so on;                           Check if a variable has been declared before using;                            derivation of type parameters for generic methods;                           Check type matching;                          Check all statements can be reached;                          Check all checked exception are captured or thrown;                &NB Sp         Checking the certainty of variablesAssignment (for example, a method with a return value must determine a return value);                          Review variable certainty Re-assignment (e.g., variables declared as final);                          de-syntax sugar (eliminate if (f alse) {...} ) Form of useless code;                          generic Java to normal java;                          The syntax tree containing the syntax sugar is changed to a syntax tree with a simple language structure, such as a foreach loop, Automatic packing/unpacking, etc.);                         .           Complete the steps above to start generating class files. The steps are:                (1) to collect the instance member initializer into the constructor and collect the static member initializer as <clinit> ();                (2) Generate byte codes from the abstract syntax tree, using the method of iterating through the syntax tree and making the final few code conversions;        & nbsp       (3) Generate class files from the symbol table. The &NBSP;2, class file contains the following information:          structure information:              class file format version number and the number and size of each part of the information.           metadata:                In simple terms, metadata corresponds to "declaring" and "constant" in Java source code. "Information.                 The main: Class/inherited superclass/implemented interface declaration information, domain and method declaration information, and constant pool.           method information:                In simple terms, the information for "statement" and "expression" in Java source code 。                 includes: Byte code, exception Processor table, evaluation stack and local variable size, type record of evaluation stack, and symbol information for debugging.   class loading mechanism. The       class loading mechanism refers to the mechanism by which your class file is loaded into the JVM and forms a class object, after which the application can instantiate and invoke the class object. 1, three steps:          load (load):                process is responsible for finding the binary bytecode and loading Into the JVM.           links (link):                process is responsible for verifying the format of binary bytecode and making the initial makeup Static variables in the load class and interfaces, classes called in the parsing class.                 Verify if not met, then throw verifyerror;            &N Bsp; The   check process will load if it encounters a reference to other interfaces and classes, and throws Noclassdeffounderror if it fails.               &NBSP;JVM Initializes a static variable in the class, assigns a default value, and finally validates all properties, methods in the class, if the stage fails, May cause nosuchmethoderror, Nosuchfielderror and other error messages.         init (init):                process is the execution of static initialization code in the class, constructor code and Initialization of static properties, the following 4 scenarios are triggered execution:                    Call new;    &NB Sp               reflection calls the methods in the class;                  The   subclass invokes the initialization class that was specified during initialization of;                    The JVM during the startup process.               &NBSP;JVM class loading is done through ClassLoader and its subclasses, divided into:          & nbsp         BootStrap Class loader;                    and nbsp     is implemented in C + + and is not a subclass of  classloader. This &nbsp is initialized when the JDK is started; classloader;                    Extension class loader;  &nbsp ;                      -some jar packages that are used to load extensions, such as the DNS tool jar package in the JDK directory;  & nbsp                 System class loader;                          to load the jar packages and directories in the classpath specified in the startup parameters.                     User-defined class loader;                      ClassLoader     developers to implement their own. Common exceptions during &NBSP;2, class loading:      (1) classnotfoundexception:                The class file was not found when the class was loaded in the current ClassLoader.       (2) noclassdeffounderror:                The original because another class referenced in the loaded class does not exist.       (3) linkageerror:               This exception is more likely to occur in the case of custom ClassLoader. The reason is that this class has already been loaded in ClassLoader and will cause the exception to load repeatedly.       (4) classcastexception:                This exception has a number of reasons, JDK5 supports generics, Reasonable use of generics can reduce the triggering of this exception relatively.   execution mechanism. 2 ways:     1, bytecode interpretation execution            compile the source code into JVM bytecode at the source compilation stage, is a way of intermediate code that is interpreted and executed by the JVM at run time.           JVM uses four instructions to perform different method calls:                (1) Invokesta tic:                    The corresponding call to the static method.                 (2) invokevirtual:              & nbsp     corresponds to the method that invokes the object instance.                 (3) invokeinterface:                    corresponding calling interface.                 (4) invokesprcial:                    corresponds to the <init> method generated after calling the private method and compiling the source code-this method is the initialization method when the object is instantiated.           JDK stack-based architecture to execute bytecode:                The thread will generate a program count after it is created (PC registers) and stack (stack).                 role:                  & NBSP;&NBSP;PC Registers: Stores the amount of compilation for the next instruction to be executed within the method.                     stacks: stack frames are stored and each method calls each one to produce a stack frame.                 stack frames are divided into: local variables and operand stacks.                 role:                  & nbsp;  Local Variables: Store local variables and parameters in the method.                     operation Stacks: intermediate results during the execution of the method of storage.                
&NBSP; local change Volume area operand stack
&NBSP; stack frame (stack frame) &NBSP;
&NBSP;
&NBSP; stack frame (stack frame) &NBSP;
pc register stack   ;
               Three ways to execute:                (1) directive Explain execution:                   : Get the next instruction, decode and assign, then execute. Because a lot of operations to put the value into the operand stack, so that the register and memory to constantly exchange data, the efficiency is not high.                    The   sun JDK is optimized for: Stack top cache and partial stack frame sharing.                                (2) stack top cache: &nbs P                   The value that would otherwise be on top of the operand stack is cached directly on the register, and for most operations that require only a single value, it is not necessary to put the data into the stack of operands. Can be calculated directly in the register, and then put back to the operand stack.                 (3) Partial stack frame sharing:                & nbsp   When a method is called, the latter method can take the operand stack of the previous method as a local variable of the current method, thereby saving the consumption of data copy.                          &NBSP;2, compile execution   &NBSP       To address the efficiency of interpreting execution, the JDK provides support for compiling bytecode into machine code, compiled at run time, often called the JIT compiler.           JDK compiles high-frequency code during execution, and continues to interpret for infrequently executed code, so the JDK is called HOTSPOTVM.           provides 2 modes of compilation: Client compiler and server compiler.           (1) client compiler:              &NBSP;C1 lightweight, with little performance Cost-optimized, low-memory footprint, suitable for interactive applications with desktop.                 on the Register allocation policy, JDK6 is used for the linear Scan register allocation algorithm.                 Other local optimization:                      Method Inline:                          The instructions for the method being called are directly implanted into the current method.                       to virtualize:      &NBsp                   After loading class, classes are parsed like a method in a class provides only one implementation class, and the code that calls this method can also be inline.                       Redundancy Elimination:                         -at compile time, depending on the run-time state The folding and elimination of code.              ,      .           (2) server compiler:              &NBSP;C2 heavyweight, a large number of traditional Optimization techniques to optimize, occupy a lot of memory, suitable for server-side applications.                 uses the traditional graph coloring register allocation algorithm. The optimization range is more about global optimization.               ( ) information collected: How often the branch jumps/does not jump, what type has occurred on an instruction, whether there has been a null value, whether there has been an exception.                 Escape analysis is the foundation of many optimizations. Refers to whether the variables in the method are read externally according to the running state, and if not, the variable is considered to be escaped. Based on this, it will do:                 at compile time.      scalar substitution:                          to replace aggregates with scalars.                           Benefits: If you create an object that does not use all of the variables, you can save a certain amount of memory 。 For code execution, it is faster because no reference to the object is needed.                     Stack:            &NBSP ;             If not, the object instance is created directly on the stack, not on the JVM heap.                         benefits: Faster allocation on the stack. As the method ends, the object is recycled.                     Sync:            &NBSP ;             If you find that the synced objects do not escape, there is no need for synchronization, and the synchronization will be removed directly at compile time.              ,      .           after run C1, C2 compiled machine code if no longer meet the optimization conditions, it will be inverse optimization, that is, back to explain the way the execution.           A special compilation is: OSR (on Stack Replace). With C1, C2 differences:                (1) OSR compilation replaces only the entry of the loop code body; phenomenon: The entire code of the method is compiled, but only the loop code body executes the compiled machine code. Other parts are still explained in the way of execution.                 (2) C1, C2 Replace the entry for the method call.          sun JDK selects C1 and C2 modes based on the machine. The default is C2 mode when the CPU exceeds 2 cores and the memory is greater than 2GB, but the 32-bit Windows machine is always C1 mode.           did not select the reason for compiling the machine code at startup:                (1) Static compilation is not based on the program Health to optimize the execution of the code.                 (2) explains that execution is more memory-efficient than compiled execution.                 (3) Start-up explaining execution is faster than compiling and restarting.           interpretation is slower during compilation, and the JDK mainly depends on whether the 2 counters on the method exceed the threshold.                 (1) calls the counter, which is the number of times the method is called. (compilethreshold)                     This value is the number of times a method is called and then compiled into a machine code. The default is 1500 times in client mode, and the default is 10,000 times in server mode.                     You can set this value by adding-xx:compilethreshold=10000 at startup. &nbSp               (2) The back-side counter, the number of times the execution of a part of the code is executed in a method. (onstackreplacepercentage)                     This value is used to calculate whether to trigger the OSR compiled threshold. By default, the client mode is 933,server mode of 140.                       This value is set by adding-xx:onstackreplacepercentage=140 at startup.           NOTE: Due to the features of the Sun JDK, in the performance testing of Java code, pay particular attention to whether or not to make a sufficient number of calls beforehand to ensure that the test is fair.          &NBSP;3, reflection implementation                 reflection and directly creating object instances, calling the maximum number of methods The same is the process of creation, method invocation is dynamic.                 The most straightforward way to make a dynamic call is to dynamically generate the bytecode and load it into the JVM for execution.  

In-depth understanding of the execution mechanism of Jvm_java code

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.