Java application performance optimization from the virtual machine perspective

Source: Internet
Author: User

Java
The platform is everywhere. Java EE, Java SE, Java me, Java card, and Java
The development of Java provides a job opportunity for countless programmers.
In addition to the syntax consistency, programmers must consider different platforms and learn the features of different platforms:

  1. Environments on different platforms

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

  2. Features of virtual machines on different platforms

    For example
    Whether multithreading is supported (this seems uncertain, but on the Java card platform, due to limited computing resources, multithreading is not currently supported), Java EE and
    Java SE has almost the same virtual machine features, while Java me
    Virtual machines (KVM) are tailored and optimized based on the characteristics of mobile devices to adapt to limited physical memory and storage space. However, they are also divided into CDC (connected) based on the processing capabilities of devices.
    Device Configuration, network device configuration) and cldc (connected limited Device
    Configuration, limited network device configuration), smaller devices and Smart Card Virtual Machine jcvm (Java card
    VM) also supports many features, such as multithreading, support for many complex data types, and proactive garbage collection mechanisms, which even leads to the cutting of Java syntax sets;

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

    Java
    EE and Java SE are the relationships between supersets and subsets, because their computer platforms and operating systems are currently well compatible, while Java me and Java card
    EE and Se are totally different, except java. Lang. *, some java. Io. * and other core class libraries are retained.
    APIs and class libraries are completely different. Java. microedition. * And javax. microedition. * indicate that this is me
    Platform, javacard. * indicates that this is a Java card platform. At the same time, because the EE and SE
    The popularity of the platform and the number of developers make the third-party libraries on the platform very large. An in-depth understanding of the platform APIs and libraries is the only way for programmers on different platforms to advance.

From this perspective, Java
Different platforms are not "one-time writing and running everywhere". When considering the design and optimization of applications, we must first look at the platforms on which they are located, because of the different features above, programming models, design patterns, and even language sets are different. Here we focus on the Java EE and Se perspectives, but there are a lot of design, programming principles and habits that apply to programmers on all platforms.

 

Java Virtual Machine


Java Virtual Machine (VM) is the basis for supporting the running of Java language, avoiding too many technical details of JVM and implementation. We understand the infrastructure and are essential for application optimization. As shown in:

Figure 1. Java virtual machine architecture


  1. Class loading Subsystem
    : Load the class into the runtime data zone by fully qualified class names (package name and class name, network load, and URL;
  2. Method Area
    : Class defines all methods and static data stored here. It is like a table or array, so that the Java bytecode and static data of the corresponding method can be found here during program execution;
  3. Java heap
    : The persistent storage area of Java objects. Objects instantiated from classes are stored here, and garbage collection is also performed here. If the space is insufficient to accommodate all objects, an out of Memory exception will be thrown, the knowledge of Java heap and garbage collection is critical to the tuning of application performance;
  4. Java stack
    : Java
    The place where the method bytecode is executed, the lifecycle of local variables in the method is in the stack, and the stack size is a key point to consider. It directly determines the number of layers of method calls, this is especially important for recursive Programs.
    Yes. The JVM we use is based on the java stack operating mechanism, and there is an exception to the implementation, Google mobile device operating system Android Virtual Machine
    Dalvik is a register-based mechanism (Dalvik supports Java Development, but from the perspective of virtual machines, it does not comply with Java
    Standard ).
  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 and the Pointer Points to the bytecode in the method area;
  6. Local method Stack
    : This is where Java calls the local library of the operating system and is used to implement JNI (Java Native Interface, Java Local interface );
  7. Execution engine
    : JVM heart, Control Loading and parsing Java bytecode;
  8. Local interface
    : Connects the local method stack and the 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
Virtual machines support fewer data types and fewer commands. Some Virtual Machine implementers add their own unique commands to optimize the performance.
Programmers are transparent. The following is an example of a Java method bytecode:


Listing 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: 0x04ad
Indicates that the next byte code to be executed is_ Invokestatic, high (0x8046), low (0x8046)
The byte code table calls a static method.

One of the major advantages of Java is that you don't have to worry about memory allocation and collection, and everything is done by the garbage collector. However, this does not mean that Java programmers can rest assured, and even more efficient collectors may cause performance problems due to abuse. We already know that the space allocation and collection involved in Java programs include:

  1. Java heap: The created Java objects (including arrays and arrays) are allocated to the heap, and garbage collection objects are released;
  2. Java stack: the stack is divided into the operand stack, stack frame data, and local variable area. The local variables allocated in the method are in the stack, at the same time, each method call will allocate stack frames in the stack. Therefore, programmers need to consider the number of call layers when designing and developing applications.

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


Listing 2. Java bytecode for integer addition


Iload_0 // load local variable 0, integer, pushed into Stack
Iload_1 // load local variable 1, integer, pushed into Stack
Iadd // Two integer numbers are displayed, and the result is added to the stack.
Istore_2 // The integer number is displayed and saved to the local variable 2.

Figure 2. integer addition operation java stack Behavior


In addition, for JVM, you also need to understand the supported data types and the space they occupy:

Figure 3. Java Data Type


 

Generation-based garbage collection mechanism

Although the implementation of various JVMs (Sun hotspot, IBM j9, Oracle jrockit, etc.) is different, the generation-based garbage collection mechanism is adopted. Spam identifies unwanted spam objects in virtual machines and deletes them to recycle space. Generation-based garbage collection algorithms are mainly divided into three types:

  • The replication algorithm divides the space into two equal-and-large parts. It accesses each associated active object starting from the root, copies all the active objects of space a to Space B, and recycles the whole space at a time.
    A. Advantage: only access an active object. After all the active objects are copied, the whole space is cleared and no dead objects are accessed. Therefore, the cost of traversing the space is small. Disadvantages: it requires a huge copy cost and a large amount of internal
    Save;
  • Mark clearing algorithm, access all active objects from the root, and mark as active objects. Then traverse the entire memory area and recycle all unmarked objects. Advantages: no additional space is required. Disadvantages: Long GC pause time, large scanning time overhead, resulting in a large amount of space fragments;
  • Mark clearing algorithm, combining the advantages of the two algorithms, first mark the active object, and then merge it into a large memory block.

Generation Division:

  • Young Generation: newly created objects are distributed here. Research shows that most of the objects produced by programs are extinct here, and almost all collectors use Replication Algorithms for young generation, the young generation is divided into one Eden zone and two surviving zones to implement Replication Algorithms;
  • Old Generation: objects that survive from the young generation are replicated to the old generation, which implements the mark clearing or mark clearing algorithm;
  • Persistent generation: The loaded class data and information are stored here, and there is no extinction object.

Java
The virtual machine provides corresponding options to set the size of the zone occupied by each generation, whether it is a Java EE server application or Java SE
For desktop applications or products, you need to analyze the creation and extinction status of the running objects and make reasonable settings of these options to achieve better performance improvement, after all, garbage collection is a time-consuming task. Reader
In order to further study related Virtual Machine options, Set Optimization values for your applications.

Garbage collection can be divided:

  • Minor collection: frequently occurs in the young generation and collects the rapidly extinct objects;
  • Main collection (major collection): full collection of young and old generations, with low frequency.

During garbage collection, all other threads on the same CPU will be blocked.
For applications, the whole world seems to be stuck. After the entire marking, clearing, and sorting cycle is completed, all application threads continue. Many JVM-implemented garbage collection mechanisms apply to multiple CPUs.
The machine environment is optimized, and the garbage collection thread and Application Thread concurrency are realized through synchronization, so that the program gets a good overall performance.

 

 

Set Virtual Machine Parameters

Set virtual machine parameters to configure the spam collector behavior and allocate the size of different zones in the heap. Different Virtual Machine implementations have different parameter options. IBM j9 virtual machines are widely used in IBM's solutions from mobile devices to enterprises. In this article, the virtual machine option parameter settings are based on IBM's j9.

After learning about garbage collection and its impact on performance, we can set GC policies based on application features for effective optimization. The related parameters are:-Xgcpolicy: [optthruput | optavgpause | GENCON | subpool]

  • -Xgcpolicy: optthruput
    For throughput optimization, This is the default GC policy for virtual machines, applicable to two extreme situations: the application needs to run as quickly as possible to end in a short time, or the application runs for a long time, there is no fixed size and distribution of throughput during operation;
  • -Xgcpolicy: optavgpause
    For GC-caused pause optimization, through concurrent execution of part of the garbage collection, compromise between high throughput and short GC pauses. The application pauses for a shorter time. Suitable for applications with comparison rules and burst throughput cycle distribution;
  • -Xgcpolicy: GENCON
    , And perform GC in different ways through generational concurrent operations to process short-lived objects and long-lived objects in different ways. When this policy is adopted, applications with many short-lived objects will show shorter pauses while still generating good throughput;
  • -Xgcpolicy: subpool
    The 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.

In addition to setting the GC policy, the most common heap size parameters are:-XMS
, Set the initial heap size;-Xmx
, Set the maximum heap space;-Xmn
, Set the size of the young generation space;-Xmo
. Programmers need to set reasonable values based on the actual machine environment and application characteristics.

 

 

Design, programming principles and habits that are easily overlooked

The knowledge of the working mechanism of virtual machines enables us to write more elegant and efficient Java code. Below are several design, programming principles and habits that are worth reference.

  • Update the Virtual Machine in time.

    Division
    Because some products must be compatible with a previous virtual machine version, we recommend that you update the runtime environment of the virtual machine deployed in the development environment and the final product to the latest version. The latest version means the latest
    API to achieve better optimization. This is applicable to embedded Java (Java me and Java
    Card) is not applicable. With the release of mobile or smart devices, virtual machines have been solidified, and new Virtual Machine versions cannot be like servers and PCs installed on EE and SE.
    Machine, easy to install. Some mobile devices can update the VM version by updating firmware and operating system programs.

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

    This
    For Java
    The performance, reuse, and maintainability of applications are particularly important. The design pattern is a general architecture summarized by masters to solve typical problems. It uses objects to describe the problem domain, use design patterns to organize actions between objects. In Design
    When solving a local problem, you must first check whether the abstract problem is consistent with the target problem of a design pattern. In addition, learn as much as possible about
    API to check whether the required functions are ready-made and available for calling. Most of the APIS implemented on the Virtual Machine Platform have good performance.

  • Concerned about java stack.

    Before
    As you can see, for stack-based Java
    Virtual machines and method calls and executions are accompanied by stack pressure and outbound operations. Each thread has its own stack. virtual machines are used to manage the stack size, but we should have a concept of its size. Stack size is a double-edged sword,
    If it is too small, it may cause stack overflow, especially when there is a recursive and large loop in the thread that is more likely to overflow. If it is too large, it will affect the number of stacks that can be created, for multi-threaded applications
    Memory overflow. Pass-XSS
    You can set the maximum value of the java stack. The default value is256 K
    . It is not recommended to set this option to another value. A good solution is to reduce the number of recursive layers through the optimization program, avoid excessive loops, and reduce the call level of the method, make your program "flat" as much as possible, and replace the in-depth method calls between a few objects with the relationship between objects as well as possible.

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

    Pass
    Dependent garbage collection may sometimes cause serious performance problems, especially when a large number of large objects are created while the program is running. A good habit is to explicitly release references without objects. In the next garbage collection cycle
    This is often ignored by Java Programmers. The legacy references will make GC unable to recycle these logically extinct objects. See the following code example:

    Listing 3. java stack



    public class Stack {
    private static final int MAXLEN = 10;
    private Object stk[] = new Object[MAXLEN];
    private int stkp = -1;

    public void push(Object p) {
    stk[++stkp] = p;
    }

    public Object pop1() {
    return stk[stkp--];
    }

    public Object pop2() {
    Object p = stk[stkp];
    stk[stkp--] = null;
    return p;
    }
    }

    The sample code is a stack structure that stores object references in the stack. The capacity is
    10. stkp is the top pointer of the stack. The Push method pushes the object into the stack. pop1 and pop2 pop up the top object of the stack. Pop1
    Directly pop up the object. This object may be released immediately after it is used by other objects, and there is still a reference pointing to this object in the stack. Because the stack may exist for a long time in the program, therefore, the pop-up objects cannot be recycled.
    Before the pop2 method pops up an object, it releases the reference of the original object held by the stack, so that the pop-up object is completely detached from the stack without affecting
    GC. Strengthening management is a good habit of creating and releasing a large number of objects in the program running. Using the object pool mechanism is a good solution. You can create a batch of objects in the object pool as needed, remove unnecessary objects
    Put it back into the pool for the next fetch and use, which greatly saves the time for repeated object creation and destruction.

    Listing 4. Java object pool code



    import java.util.HashMap;
    import java.util.LinkedHashSet;

    public class ObjectFactory {

    /** A counter for counting the number of objects in use. */
    private static int objInUse = 0;

    /** A counter for counting the number of objects in pool. */
    private static int objInPool = 0;

    /** The object pool. */
    private static HashMap objectPool = new HashMap();

    /** The corresponding object pool for a specific class. */
    private static LinkedHashSet subObjPool;

    /** Generate object for use */
    public synchronized static Object generate(String className) {

    Object retObj = null;

    subObjPool = (LinkedHashSet) objectPool.get(className);

    if (subObjPool != null && subObjPool.size() < 0) {

    retObj = subObjPool.iterator().next();
    subObjPool.remove(retObj);
    objInPool--;

    } else {

    try {

    retObj = newObj(className);

    } catch (InstantiationException ie) {
    return null;
    } catch (IllegalAccessException iae) {
    return null;
    } catch (ClassNotFoundException cnfe) {
    return null;
    }
    }

    objInUse++;

    return retObj;
    }

    public synchronized static void drop(Object freeObject) {

    if (freeObject != null) {

    subObjPool = (LinkedHashSet) objectPool.get(className);

    if (subObjPool == null) {
    subObjPool = new LinkedHashSet();
    objectPool.put(className, subObjPool);
    }

    if (!subObjPool.contains(freeObject)) {
    subObjPool.add(freeObject);
    objInPool++;
    objInUse--;
    }

    }
    }

    /** Counts the number of objects which are in use now. */
    public static int countObjectInUse() {
    return objInUse;
    }

    /** Checks the current size of the object pool. */
    public static int checkPoolSize() {
    return objInPool;
    }

    /** New object for class name. */
    private static Object newObj(String className)
    throws InstantiationException, IllegalAccessException,
    ClassNotFoundException {

    Object obj = Class.forName(className).newInstance();
    return obj;
    }
    }

Java profiler Tool


Java
Profiler uses JMX (Java Management Extensions, Java resource management framework) or jvmpi (Java
Virtual Machine profiler interface, Java Virtual Machine Monitoring Program Interface)
Resources and application objects in virtual machines. Profiler
The tool monitors object allocation and collection, heap space, thread running, thread deadlock, and network status. This is Java
The programmer's performance analysis provides the starting point. By analyzing the running status of the program, the programmer can quickly locate the problem and optimize it. The Java profiler tool analyzes Java
The program performance is a good helper, but in the final analysis, the performance improvement depends on the programmer's understanding of the Java Virtual Machine, and follows the good design and development principles on this basis. This is also Java
The only way for programmers to become real masters.

For details about how to use the profiler tool, refer to the relevant resources for in-depth research. Common Java profiler tools include:

  • Jconsole
    The Virtual Machine SDK comes with a tool. After the Java SDK is installed, start it in the/bin directory;
  • Eclipse tptp (test and Performance Tools platform)
    Is a tool plug-in for testing and performance monitoring provided by eclipse.org's top-level project;
  • Netbeans profiler
    Sun is built into the profiler in netbeans to facilitate development in netbeans;
  • Visual VM
    Initially, profiler released by Sun with JDK 6 update 7, visual VM contains jconsole, and the interface is more beautiful and easy to use.

 

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.