Java application performance optimization from the virtual machine perspective

Source: Internet
Author: User
Tags jconsole netbeans java se

Before getting started

Java platform is already ubiquitous Java EE Java SE and Java me and Java card Java has developed into numerousProgramThey provide job opportunities in Java. However, apart from the basic Java

    1. Environments on different platforms

      Java EE running hardware server, operating system, architecture of the PC where Java SE is located (x86/x64, Mac) and the type of the smart card chip where the Java card of the mobile phone or mobile device running in Java me is located;

    2. Features of virtual machines on different platforms

      For example, whether multithreading is supported (this seems to be beyond doubt, but on the Java card platform, due to limited computing resources, multithreading is not supported yet) java EE and Java SE have almost the same virtual machine features, while Java me'sCDC (connection device configuration, network device configuration) and cldc (limited connection device configuration, network connection device configuration), more uploaded device and Smart Card Virtual Machine jcvm (Java cardJava syntax set pruning;

    3. APIs on different platforms and available third-party Libraries

      Java EE and Java SE of Java me and Java card and EE and Se are completely different, except java. Lang. *, Some java. Io. * and other core class libraries are retained, and other APIs and class libraries are completely different. Java. microedition * And javax. Microedition. It indicates that this is the me platform, Java card. Indicates that this is a Java card platform. At the same time, EE and Se APIs and libraries are the only way for programmers on different platforms to advance.

From this perspective, Java EE and SE

Back to Top

Java Virtual Machine

Java Virtual Machine (VM) is the basis for running the supported Java language, avoiding excessive JVM

Figure 1. Java virtual machine architecture
 

    1. Class loading SubsystemLoad the class into the runtime data zone using the fully qualified class name (package name and class name, network load, and URL;
    2. Method Area: Class for all method extensions and static Java bytecode and static data;
    3. Java heap: Exceptions with insufficient Java memory will be thrown out. The knowledge of Java heap and garbage collection is critical to the performance tuning of applications;
    4. Java stack: Java resource JVM is a Java-based stack operating mechanism, with an exception, dalvik, the android Virtual Machine of Google's mobile device operating system, is based on the register mechanism (Dalvik supports Java language development, but from the perspective of virtual machines, does not comply with Java standards). For the Comparison Between Stack and register mechanisms for Virtual Machine implementation, refer to the Extended Function of the paper "Virtual Machine showdown: Stack battle register";
    5. Program counters: For stack-based JVM, this is almost a unique register. It is used to indicate which Java bytecode is executed by the current Java execution engine, the Pointer Points to the bytecode of the method extended functional area;
    6. Local method Stack: This is where Java calls the local database of the operating system and is used to implement JNI (Java Local interface of the Java Local interface );
    7. Execution engine: The Heart of JVM, control the loading of Java bytecode and parse;
    8. Local interface: Connects the local method extended function stack and operating system library.

Java bytecode is a JVM command. All Java platform virtual machines have their own instruction sets, while most of the commands are the same, about 200 in total. Java card Java programmers are transparent. Below is an example of the Java method extension function bytecode:


List 1. Java bytecode example

/* 0x000092c4: 0x04a7: */_ sconst_0,/* 0x000092c5: 0x04a8: */_ sconst_0,/* 0x000092c6: 0x04a9: */_ invokestatic, high (0x08e8 ), low (0x08e8)/* 0x000092c9: 0x04ac: */_ pop,/* 0x000092ca: 0x04ad: */_ invokestatic, high (0x8046), low (0x8046 ),/* 0x000092cd: 0x04b0: */_ ifeq, 84,/* 0x000092cf: 0x04b2: */_ invokestatic, high (0x8044), low (0x8044 ), /* 0x000092d2: 0x04b5: */_ Goto, 79,/* 0x000092d4: 0x04b7 */_ astore, 7,

 

When the value of the program counter is0x000092ca: 0x04adIndicates that the next byte code to be executed is_ Invokestatic, high (0x8046), low (0x8046)The byte code table calls a static method.

The space allocation and collection involved in Java programs include:

    1. Java
    2. Java

Let's look at the execution example of a piece of bytecode In the java stack. 100 and 98 are added:


List 2. Java bytecode for integer addition

Iload_0 // load the local variable, integer, and press iload_1 in the stack. // load the local variable, integer, and iadd in the stack. // Two integer values are displayed and added, press the result into the stack istore_2 // The integer number is displayed and saved to local variable 2.

Figure 2. Java stack behavior of integer addition operations
 

In addition, for JVM, you also need to understand the supported data types and. Space occupied by cl1:


Figure 3. Java Data Type
 

Back to Top

Generation-based garbage collection mechanism

Although various JVM implementations (Sunday hotspots, Oracle jrockit, IBM j9

    • All active objects of a are copied to Space B, and the whole space is recycled at one time.
    • GC pause time, large scanning time overhead, resulting in a large amount of space fragments;

Generation Division:

    • One Eden zone and two surviving zones are used for replicationAlgorithm;
    • Old Generation: objects that survive from the young generation are replicated to the old generation, which implements the mark clearing or mark clearing algorithm;
    • Permanent generation: The mounted class data and information are stored here, and there is no extinction object.

Java virtual machines provide corresponding options to set the size of the occupied area of each generation, whether it is a Java EE server application or Java SE

Garbage collection can be divided:

    • Secondary collection (small collection): frequent occurrence of young generation, and collection of fast-disappearing objects;
    • Primary collection (primary collection): full collection of young and old generations with low frequency.

During the garbage collection operation, all other threads on the same CPU will be blocked. Therefore, the garbage collection mechanism implemented by Java JVM applies to multiple CPUs.

Back to Top

Set Virtual Machine Parameters

J9 Virtual Machine in IBM j9.

The GC policy is effectively optimized. The related parameters are:-Xgcpolicy: optthruput | optavgpause | GENCON subpool]

    • Xgcpolicy: optthruputFor effective output optimization, which is the default GC for virtual machines
    • Xgcpolicy: optavgpauseFor GC-caused pause optimization, through concurrent execution of part of the garbage collection, high-efficiency output and short GC
    • Xgcpolicy: GENCON, Generation-based concurrency
    • -Xgcpolicy: subpoolThe sub-pool is optimized using an algorithm similar to the Default policy, but a allocation policy suitable for multi-processor computers is adopted. It is applicable to multi-threaded applications that run in a multi-core environment with a high object creation rate.

Besides setting GC

Back to Top

Easily overlooked design, programming principles and habits

The knowledge of the working mechanism of virtual machines makes us sure to write more elegant and efficient JavaCode. The following are some design, programming principles and habits worth reference.

  • Update the Virtual Machine in time.

    API to achieve better optimization. This is an update to the version of the embedded Java (Java me and Java EE and Se installed servers and pc vms.

  • Good object-oriented design and architecture, application design model.

    For Java APIs, check whether the required functions are ready-made and can be called. Most of the APIS implemented on the Virtual Machine Platform have good performance.

  • Java stack.

    As we have learned before, for the Java

  • Enhance object management, so you do not have to let yourself flow.

    Java programmers ignore that legacy references will cause GC to fail to recycle these logically extinct objects. See the following code example:

    Listing 3. Java stack

    Public class Stack {Private Static final interpretation maxlen = 10; private object STK [] = new object [maxlen]; private stkp =-1; Public invalid push (Object P) {STK [++ stkp] = P;} public objectPop1() {Return STK [stkp-];} public objectPop2() {Object P = STK [stkp];STK [stkp-] = NULL;Returns P ;}}

    The sample code is a stack structure that stores object references in the stack. The capacity is 10, and stkp is the top pointer of the stack. The method extension function pushes the object into the stack, pop1 and pop2 pop up the stack top object. Pop1

    Listing 4. Java object pool code

    The imported java. util. hashmap; the imported java. util. javashashset; The objectfactory {/** counter of the public class, which is used to count the number of objects in use. */Private static interpretation objinuse = 0;/** a counter used to count the number of object pools. */Private static interpretation objinpool = 0;/** Object pool. */Private Static hashmap objectpool = new hashmap ();/** the object pool corresponding to a specific class. */Subobjpool of Private Static linkedhashset;/** used to generate objects */{object retobj = NULL of string classname generated by synchronizing static objects; objectpool in subobjpool = (linkedhashset. get (Class Name); If (subobjpool! = Returns NULL & subobjpool. size () <0) {retobj = subobjpool. under iterator (); subobjpool. remove (retobj); objinpool-;} else {try {retobj: = newobj (Class Name);} catch (instantiationexception) {return NULL;} catch (illegalaccessexception IAE) return NULL;}'s catch (classnotfoundexception exception cnfe) returns NULL;} objinuse ++; returns retobj;} public static invalid synchronous descent (Object freeobject) {(freeobject! = NULL) {subobjpool = (excluding hashset) objectpool. get (Class Name); If (subobjpool = NULL) {subobjpool = () of the new javashashset; objectpool. put (Class Name subobjpool);} If (! Subobjpool. Contains (freeobject) {subobjpool. Add (freeobject); objinpool ++; objinuse-;}}/ ** the number of objects currently in use is counted. */Public static interpretation of countobjectinuse () {returns objinuse;}/** check the current size of the Object pool. */Public static interpretation of checkpoolsize () {returns objinpool;}/** the name of the new object class. */An instantiationexception, illegalaccessexception, and classnotfoundexception exception is thrown for a private static object newobj (string class name). {object OBJ = Class. forname (class name) is called ). Newinstance (); returns OBJ ;}}

Back to Top

Java event probe Tool

Java event Probes Use JMX (Java Management extension, Java resource management framework) or jvmpi (Java Virtual Machine event probe interface, Java Virtual Machine Monitoring Program Interface) java Virtual Machine resources, application objects, and other monitoring tools. The Java event probe tool is a good helper for analyzing the Java program performance. However, in the final analysis, the performance improvement depends on the programmer's understanding of the Java Virtual Machine, on this basis, good design and development principles are followed. This is also the only way for Java programmers to become masters.

For more information about how to use analyzer tools, see related resources for further research. Common Java event probe tools include:

    • JconsoleThe Virtual Machine SDK comes with a tool. After installing the Java SDK, start it in the/bin directory;
    • Eclipse testing and performance tool platform (tptp)Is a tool plug-in for testing and performance monitoring provided by eclipse.org's top-level projects;
    • SunNetbeans profiler willBuilt-in in netbeans, which is easy to use during netbeans development;
    • Visual VMInitially, Sun released the analyzer with JDK 6 update 7. The visual Virtual Machine contains jconsole, and the resource classification interface is more beautiful and easy to use.

Back to Top

Conclusion

From the perspective of Java virtual machines, this article analyzes how to improve the performance awareness and level with Java programmers.

 

References

Learning

    • Read Sun's White Paper on Java optimization.

    • Read the Sun Java Virtual Machine hotspot architecture White Paper.
    • Learn more about real-time Java technology.
    • View articles related to ibm jdk analysis and diagnosis.
    • Understand the Garbage Collector of Java virtual machines implemented by IBM.
    • Learn more about open-source analyzer tools from the list of open-source Java event promizer tools.
    • Understand jvmpi technology.
    • See visual VM on the visual VM homepage.
    • Java Technology Zone on developerworks: find hundreds of articles on Java programmingArticle.

Obtain products and technologies

    • Download the IBM software trial to experience the powerful WebSphere software Tivoli and rational when it is easy to get started with Lotus.

Discussion

      • View the latest information about the developerworks blog.

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.