Java Virtual Machine 11: Run-time optimization

Source: Internet
Author: User

Objective

Http://www.cnblogs.com/xrq730/p/4839245.html,HotSpot uses the Interpreter + compiler co-existence of the architecture, the previous article has been mentioned, this article just put the real-time compiler this piece to speak more specific. Of course, in fact, the content of this article does not have much significance, 90% is the concept of things, for the actual development, the actual solution of the problem within the project is not much help, as long as you have seen the good.

compiling objects and triggering conditions

As mentioned before, the virtual machine used by Sun is called "Hotspot", because the hot code is detected in the process of running, there are two types of "hot code" that will be compiled by the instant compiler during the running process, namely:

    • Methods that are called multiple times
    • The loop body that was executed multiple times

The former is very good understanding, a method is called much more, the method body code executes more naturally, he became "hot code" is also taken for granted. The latter is to solve a method has been called only once or a few times, but there are many loops in the method body problem, so that the loop body code is repeated several times, so the code should also be considered "hot code".

In the above problem description, the so-called "many times" is not a specific, rigorous terminology, then how many times is counted "many times"? Also, how many times do virtual machines count a method or a piece of code?

Judge a piece of code is not hot code, it is necessary to trigger the immediate compilation, such behavior is called " Hot Spot Detection ", in fact, hot spot detection does not have to know how many times the method is called, the main hot spot detection methods have two kinds:

    • Sampling-based hotspot detection
    • Hot spot detection based on counter

The second counter-based hotspot detection method is used in the Hotspot virtual machine, which prepares two types of counters for each method: The method call counter and the back edge counter. In determining the virtual machine running parameters, both counters have a certain threshold value, when the counter exceeded the threshold overflow, it will trigger JIT compilation, respectively, look at:

1. Method call counter

As the name implies, this counter is used to count how many times the method is called, and its default threshold is 1500 times in client mode, 10,000 times in server mode. This threshold can be set artificially by the parameter-xx:compilethreshold. When a method is called, it checks to see if there is a JIT-compiled version of the method, and if it does, it takes precedence over the compiled native code. If no compiled version exists, the call counter value of this method is incremented by 1, and the sum of the method call counter and the back edge counter value is determined to exceed the threshold value of the method call counter. If the threshold is exceeded, a code compilation request for the method is submitted to the immediate compiler.

If this parameter does not make any settings, then the method call counter counts not the absolute number of times the method was called, but rather a relative frequency of execution, that is, the number of times the method was called within a period of time. When more than a certain time limit, if the number of calls to the method is still not enough to submit it to the immediate compiler compile, then this method of the call counter will be less than half, this process is called the method of the call counter heat attenuation, and this time is called this method statistics of the semi-decay period. The action of heat attenuation is in the same way that the virtual machine is garbage collected, you can use the virtual machine parameter-xx:-usecounterdecay to turn off the heat attenuation, so that the method counter counts the absolute number of method calls, so that, as long as the system is running long enough, Most methods will be compiled with cost code . In addition, you can use the-xx:counterhalflifetime parameter to set the time of the half-decay period, in seconds.

If the parameter is not set, the execution engine does not wait for the compilation request to complete, but instead goes directly to the interpreter to execute the bytecode as interpreted, until the submitted request is compiled by the compiler. When the compilation is completed, the call entry address for this method is automatically rewritten by the system to be new, and the compiled version is used the next time the method is called.

2, Back side counter

Its function is to count the number of times a loop body code is executed in a method, and the instruction called "Back edge" when it encounters a control flow after a byte code. Obviously, the purpose of the statistics is to set up the back-edge technology to trigger the OSR compilation. With respect to the threshold value of the back edge counter, although the hotspot also provides a parameter similar to the method call counter threshold-xx:compilethreshold-xx:backedgethreshold for the user to set, the current virtual machine does not actually use this parameter, So we need to set another parameter-xx:onstackreplacepercentage to indirectly adjust the threshold value of the back edge counter, the formula is as follows:

(1) Client mode

The method calls the counter threshold XOSR ratio/1000, where the OSR ratio defaults to 933, and if all defaults are taken, the threshold value for the client mode next-edge counter should be 13995

(2) Server mode

The method call counter threshold X (OSR ratio-interpreter monitor ratio)/100, where the OSR ratio defaults to 140, the interpreter monitors the ratio by default of 33, and if all defaults are taken, the server mode next-edge counter threshold value should be 10700

When the interpreter encounters a back-side instruction, it will first find out if there is a compiled version of the code fragment to be executed, and if so, it will take precedence over the compiled code, or add 1 to the value of the back-side timer, and then determine whether the sum of the method call counter and the back-edge counter value has exceeded the threshold of the back When the threshold is exceeded, a OSR compile request is submitted, and the value of the back-side counter is lowered to continue the loop in the interpreter, waiting for the compiler to output the compiled result.

Unlike the method counter, the back-edge counter has no heat decay, so this counter counts the absolute number of times that the method is executed in a loop. When the counter overflows, it also adjusts the value of the method counter to the overflow state so that the standard compilation process is performed the next time the method is entered.

Compilation process

It is easy to pass through the content of this compilation process, because this is primarily the compilation principle and the content in code optimization.

Under the default settings, either the immediate compilation request produced by the method call or the OSR compile request, the virtual machine continues to execute in an interpreted manner while the code compiler is not finished, while the compilation action is performed in the compilation thread in the background. The user can suppress background compilation through-xx:-backgroundcompilation, after the background compilation is suppressed, once the JIT compilation condition is reached, the execution thread submits the compilation request to the virtual machine and waits until the compilation process is complete before it starts executing the native code of the compiler output.

For the client Compiler (C1 compiler), it is a simple and fast three-segment compilation, the main focus is the local optimization, and abandoned a lot of time-consuming global optimization means.

For the sever Compiler (C2 compiler), it is a typical service-oriented application and a specially tuned compiler for the performance of the server, and a fully optimized high-level compiler that can almost meet the optimization strength of the GNU C + + compiler when using-O2 parameters, It performs all the classic optimization actions, such as useless code elimination, looping expansion, constant propagation, basic block reordering, and other optimizations that are closely related to the Java language features, such as scope check elimination, NULL check elimination, and possibly, depending on the interpreter or client Compiler provides performance monitoring information to perform some unstable radical optimizations, such as Guardian inline, branch frequency prediction, and the next section will explain some of the above optimization techniques.

The Server compiler is undoubtedly slower from the standard of instant compilation, but it compiles much faster than the traditional static optimization compiler, and it improves the code quality of the compiler output relative to the client compiler, reducing the execution time of the local code. This offsets the additional compile-time overhead, so there are many non-server-side applications that choose to run with a virtual machine that is in servers mode.

Optimization technology

On the Sun's official wiki, the hotspot virtual machine design team lists a relatively comprehensive list of optimizations that are used in the instant compiler, with many optimizations for classic compilers, There are also many optimization techniques for the Java language (which is exactly the language that runs on Java virtual machines), and the following are some of the most representative optimization techniques:

    • One of the classic optimization techniques that are not language-Independent: Common sub-expression elimination
    • One of the classic optimization techniques of language Independence: Array range Check elimination
    • One of the most important optimization techniques: Method Inline
    • One of the most cutting edge optimization techniques: Escape analysis

1, common sub-expression elimination

Common subexpression elimination means that if an expression e has already been computed and all the variable values from the previous calculation to e are not changed, then the appearance of e becomes a common subexpression . For this type of expression, it is not necessary to take the time to calculate it, just use the previously computed expression results instead of E. If this optimization is limited to the basic block of a program, it is called local common subexpression elimination, and if the scope of this optimization covers more than one base block, it is called global common subexpression elimination. For a simple example, suppose the following code exists:

int d = (c * b) * * A + (A + b * c);

If this code is given to the Javac compiler, no optimizations will be made. But after this code goes into the virtual machine instant compiler, it will be optimized as follows, and the compiler detects that "C * b" and "B * C" are the same expressions, and that the value of B and C is constant during the calculation, so this expression will be treated as:

int d = e * + A + (A * E);

At this point, the compiler may also perform another optimization called algebraic simplification, which changes the expression to:

int d = E * + A * 2;

After the expression is transformed, you can save some time in the calculation.

2. Array range Check elimination

We know that the Java language is a dynamic and secure language, read and write access to the array is not like C, C + + is essentially a bare pointer operation, if there is an array foo[], in the Java language access to the array element Foo[i] will automatically do the upper and lower bounds of the scope of the check, that is, check i>= 0&&i<foo.length this condition, otherwise an array subscript out-of-bounds exception will be thrown. This is a good thing for developers, even if the programmer does not specifically write defense code, but also to avoid the majority of overflow attacks, but for the virtual machine, each time the array elements read and write with an implicit conditional judgment operation, for a large number of array access to the program code, is undoubtedly a performance burden.

In any case, for the sake of security, array bounds checking must be done, but it is negotiable that the array bounds check is not required to be checked once during the run. For example, the array subscript is a constant, as long as the compilation period according to data flow analysis to determine the value of the foo.length, and to determine whether the subscript is not out of bounds, the implementation of the time will not need to judge. The more common case is that array access occurs in a loop, and the loop variable is used for array access, and if the compiler can determine that the value range of the loop variable is always within the interval [0, foo.length) through data flow analysis, the entire loop can eliminate the upper and lower bounds of the array, This can save many times the conditional judgment operation.

3. Method inline

One of the most important optimization tools. It has two main purposes: to remove the cost of the method call (such as building a stack frame, etc.), for other optimizations to establish a good foundation , the method of inline expansion can be easily in a wider range of subsequent optimization methods. Method inline for an example:

 Public Final int Geta ()
{
Geta () statement 1;
Geta () statement 2;
Geta () statement 3;
Geta () statement 4;
Geta () statement 5
}
 Public Static void Main (string[] args) {    main statement 1;    Main statement 2;     int i = geta ();    Main statement 3;    Main statement 4}

After optimization, it becomes:

 Public Static void Main (string[] args) {    main statement 1;    Main statement 2;    Geta () statement 1;    Geta () statement 2;    Geta () statement 3;    Geta () statement 4;    Geta () statement 5;    Main statement 3;    Main statement 4}

From the effect, nothing but the Geta () method to get the contents of the main function intact, but this is less to protect the scene, restore the thread, build stack frame and a series of work, and code a swell, the original method A has 5 lines of code, method B has 6 lines of code, method C has 7 lines of code, There may not be much optimization for each of the three methods, but the three methods fit together into the main function, and there is a lot of room for optimization.

In this case, do we understand why we should try to declare the method as final? Because Java has polymorphic existence, the runtime calls which method can be determined according to the actual subclass, greatly enhancing the flexibility, but in this case, the compilation also cannot determine which version should be used, so cannot be inline. However, the methods declared as final are different, these methods cannot be overridden, so the B method of Class A is called, and the runtime invocation is necessarily the B method of Class A, which can be inline.

4. Escape analysis

At present, the advanced optimization technology in Java Virtual machine is not the means of directly optimizing code, but provides analysis technology for other optimization methods.

The basic behavior of the escape analysis is to analyze the object's dynamic scope: When an object is determined in a method, it may be referenced by an external method, for example, as a calling parameter to another method, called a method escape. It may even be accessed by external threads, such as assignment to class variables or instance variables that can be accessed in other threads, called thread escapes.

If you can prove that an object does not move outside the method or thread, that is, other methods or threads cannot access the object in any way, you might have some efficient optimizations for that variable:

(1) on-Stack allocation

In a Java virtual machine, objects are distributed on the heap as well known. The garbage collection system of a virtual machine can reclaim objects that are no longer used in the heap, but the recycling action is time-consuming whether to filter recyclable objects or reclaim and defragment memory. If it is determined that an object does not escape out of the way, it would be a good idea to have the object allocated on the stack, and the memory space occupied by the object can be destroyed as the stack frame stacks up, so that the pressure on the garbage collection system will be much smaller.

(2) Synchronous elimination

Thread synchronization itself is a relatively time-consuming process, if the escape analysis can determine that a variable does not escape the thread, can not be accessed by other threads, then the variable read and write must not have a neck pillow, this variable implementation of the synchronization measures can be eliminated

(3) Scalar substitution

Scalar refers to the fact that a data can no longer be decomposed into smaller data to represent that the basic data types in Java, which are reference types, cannot be further decomposed, so they are called scalars. In contrast, if a data can continue to decompose, then it is called aggregation, and the object in Java is the most typical aggregation amount. If the escape analysis proves that an object will not be accessed externally and that the object can be disassembled, then the program will probably not create the object when it is actually executed, instead of creating a number of the member variables that are used by the method instead. After splitting an object, you can create conditions for further optimizations, in addition to allowing members of the object to be allocated and read and written on the stack.

The paper on Escape analysis was published in 1999, but it was not until Sun JDK1.6 realized the escape analysis, and until now the optimization was not mature enough, there was still much room for improvement. The main reason for immaturity is that the performance gains of escape analysis must be higher than its consumption. Although in the actual test results, the implementation of the escape analysis of the program can often run a good result, but in the actual application, especially in large programs found that the implementation of escape analysis may appear to be unstable, or because the analysis process time-consuming but can not effectively identify non-escaping objects resulting in performance degradation.

If necessary, and confirm that the program is useful to run, you can use the parameter-xx:+doescapeanalysis to manually open the escape analysis, after opening can be used to view the analysis results by parameter-xx:+printescapeanalysis. With escape analysis support, you can use parameter-xx:+eliminateallocations to turn on scalar substitution, use parameter-xx:+eliminatlocks to turn on sync elimination, use parameters-xx:+ Printeliminateallocations See the substitution of scalars.

Although the current escape analysis technology is still not very mature, but in the future of virtual machines, the escape analysis technology will certainly support a series of practical and effective optimization techniques

Java Virtual Machine 11: Run-time optimization

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.