JVM performance optimization Best Practices
With the popularization and wide application of Java, JVM performance optimization becomes more and more important. This article analyzes Java application design considerations from the perspective of JVM virtual machines, especially the garbage collection mechanism, it also summarizes several design and coding principles that are easily overlooked in the development process.
1. Before optimizing JVM, let's first understand the JVM architecture.
1. Class loading subsystem: load the Class into the runtime data zone by fully qualified Class names (package name, Class name, network load, and URL;
2. Method Area: The Class defines all methods and static data stored here. It is like a table or array, let the program find the Java bytecode and static data of the corresponding method here during 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 currently, an Out Of Memory exception will be thrown Out. The awareness Of Java heap and garbage collection is critical to the performance tuning Of applications;
4. Java stack: where the bytecode of the Java method is executed, the lifecycle of local variables in the method is in the stack. The size of the stack is a key point to consider, it directly determines the number of layers of method calls, which is especially important for recursive Programs. The JVM we use is based on the Java stack running mechanism, and there is an exception implementation, the Virtual Machine Dalvik of Google's mobile device operating system Android is a register-based mechanism (Dalvik supports Java language development, but it does not comply with Java standards from the virtual machine perspective ), for more information about the Stack and register mechanisms for Virtual Machine implementation, see "Virtual Machine Showdown: Stack Versus Registers ";
5. program counter: 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 bytecode pointing to 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: the heart of JVM, which controls loading and parsing Java bytecode;
8. Local interface: connects the local method 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. The Java Card Virtual Machine supports less data types, there are fewer commands. Some Virtual Machine implementers add their own unique commands to optimize the performance, which is transparent to Java programmers.
Ii. Next, let's take a look at the JVM garbage collection mechanism.
JVM adopts a generation-based garbage collection mechanism. 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:
1. Copy the algorithm and divide the space into two equal-and-greater parts. Access each associated active object from the root, and copy all the active objects of space A to Space B, then, the whole space is reclaimed at one time. Advantage: only access the 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, disadvantage: it requires a huge copy cost and a large amount of memory;
2. Mark the clearing algorithm, access all active objects from the root, and mark them 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;
3. Mark clearing algorithm. Combining the advantages of the two algorithms, we first mark the active objects and merge them into large memory blocks.
Iii. Let's introduce the division of JVM generation again:
1. Young Generation: newly created objects are distributed here. Studies show 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;
2. Old Generation: objects that survive from the young generation are copied to the old generation, and the mark clearing or mark clearing algorithm is mainly implemented;
3. Permanent generation: The mounted class data and information are stored here, and there are no dead objects.
The Java 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 a Java SE desktop application or product, you need to analyze the creation and extinction status of objects during the runtime and set these options properly to achieve better performance. After all, garbage collection is a time-consuming task.
4. Let's take a look at the JVM garbage collection frequency:
1. Secondary Collection: frequently occurs in the young generation, and the objects that rapidly die out are collected;
2. Main Collection (Major Collection): full-range Collection of young and old generations with low frequency.
When garbage collection is running, all other threads on the same CPU will be blocked, so for Java applications, the whole world seems to be stuck, after the entire marking, clearing, and sorting cycle is completed, all application threads can continue. Many JVM-implemented garbage collection mechanisms optimize the multi-CPU machine environment, through synchronization, the garbage collection thread and application thread are concurrent, so that the program gets a good overall performance.
4. Finally, let's take a look at how to adjust and optimize VM 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.
After learning about garbage collection and its impact on performance, we can set GC policies based on application features for effective optimization. -Xgcpolicy: [optthruput | optavgpause | gencon | subpool]
-Xgcpolicy: optthruput for throughput optimization. This is the default GC policy for virtual machines. It is applicable to two extreme situations: the application needs to finish running as quickly as possible within a short time, or the application runs for a long time, there is no fixed size and distribution of throughput during operation;
-Xgcpolicy: optavgpause, which is used for GC-caused pause optimization. It executes part of garbage collection concurrently to 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, which performs GC in multiple generations concurrently. Short-lived objects and long-lived objects are processed 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, Which is optimized by sub-pools. It adopts an algorithm similar to the Default policy, but adopts a allocation policy suitable for multi-processor computers. 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: set the size of the old generation space. We need to set reasonable values based on the actual machine environment and application characteristics.
5. design, programming principles, habits, and optimization suggestions that are easily overlooked during development
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.
1. Update the Virtual Machine in time
In addition to the compatibility requirements of some products, we recommend that you update the runtime environment of virtual machines deployed in the development environment and final product to the latest version. The latest version means the latest API and better optimization.
2. Good object-oriented design and architecture, Application Design Model
This is particularly important for the performance, reuse, and maintainability of Java applications. The design pattern is a general architecture summarized by masters to solve typical problems and describes the problem domain with objects, use design patterns to organize actions between objects. When designing and solving local problems, you must first check whether the abstract problems are consistent with the objective problems of a design pattern. In addition, learn as much as possible about the APIS supported by virtual machines, and check whether the required functions are ready-made and available for calling. Most of the APIS implemented by the Virtual Machine Platform have good performance.
3. Care About Java stack
As we have learned before, for stack-based Java virtual machines, method calling and execution are accompanied by stack pressure and stack exit 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. The 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, it is more likely to overflow. If it is too large, this will affect the number of stacks that can be created. If it is a multi-threaded application, it will cause memory overflow. You can set the maximum value of the Java stack through-Xss. The default value is 256 kb. 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.
4. Strengthen object management, so you do not have to let yourself stream.
Excessive dependency on garbage collection may sometimes cause serious performance problems, especially when a large number of objects are created while the program is running. A good habit is to explicitly release references that do not use objects and be recycled in the next garbage collection cycle, which is often ignored by Java programmers, legacy references will cause GC to fail to recycle these logically extinct objects, resulting in Memory leakage.