Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of JVM

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you the example analysis of JVM, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Tracing back to the Source-- Heap and Stack

Heap is usually an array object that can be thought of as a tree. Stack is a linear table that can only insert and delete at one end. The essence of JVM is heap and stack.

First, from a software design point of view, the stack represents the processing logic, while the heap represents the data. This separation makes the processing logic clearer. The idea of divide and rule. This idea of isolation and modularization is reflected in all aspects of software design.

Second, the separation of the heap from the stack enables the contents of the heap to be shared by multiple stacks (which can also be understood as multiple threads accessing the same object). There are a lot of benefits from this sharing. On the one hand, this sharing provides an effective way of data interaction (such as shared memory), on the other hand, shared constants and caches in the heap can be accessed by all stacks, saving space.

Third, the stack needs to divide the address segment because of the needs of the runtime, such as saving the context in which the system is running. Because the stack can only grow upward, it limits the ability of the stack to store content. Unlike the heap, the objects in the heap can grow dynamically as needed, so the split of the stack and the heap makes dynamic growth possible, and only one address in the heap needs to be recorded in the corresponding stack.

Fourth, object-oriented is the perfect combination of heap and stack. In fact, there is no difference in execution between object-oriented programs and previously structured programs. However, with the introduction of object-oriented, the way of thinking about problems has been changed, and it is closer to the natural way of thinking. When we take the object apart, you will find that the properties of the object are actually data stored in the heap, while the behavior (method) of the object is to run the logic and put it on the stack. When we write objects, we actually write both the data structure and the logic to deal with the data. I have to admit that object-oriented design is really beautiful.

JVM operation mechanism

This figure shows the memory structure of jvm

The JVM memory structure mainly consists of two subsystems and two components. The two subsystems are Classloader subsystem and Executionengine (execution engine) subsystem, and the two components are Runtimedataarea (runtime data area) component and Nativeinterface (local interface) component.

The role of the Classloader subsystem: load the contents of the class file into the methodarea (method area) in Runtimedataarea based on a given fully qualified class name (such as java.lang.Object). Java programmers can write their own Classloader with the extendsjava.lang.ClassLoader class.

The role of the Executionengine subsystem: to execute instructions in classes. The core of any JVMspecification implementation (JDK) is Executionengine, and the quality of different JDK such as Sun's JDK and IBM's JDK mainly depends on the quality of their respective Executionengine.

Nativeinterface component: interacts with nativelibraries and is an interface for interaction with other programming languages. When you call the native method, you enter a whole new world that is no longer limited by virtual machines, so it's easy to have nativeheapOutOfMemory that JVM can't control.

RuntimeDataArea component: this is what we often call JVM memory.

Life cycle of JVM

First, two concepts are analyzed.

JVM instance and JVM execution engine instance

(1) the JVM instance corresponds to an independent java program, which is at the process level.

(2) the instance of JVM execution engine corresponds to the thread that belongs to the user running program, which is thread-level.

II. The life cycle of JVM

(1) the birth of JVM instance: when a Java program is started, a JVM instance is generated, and any class with public static void main (String [] args) function can be used as the starting point for JVM instance to run.

(2) the running main () of the JVM instance is the starting point of the program's initial thread, and any other thread is started by that thread. There are two kinds of threads inside JVM: daemon thread and non-daemon thread. Main () is a non-daemon thread, which is usually used by JVM itself. Java programs can also indicate that the thread they create is a daemon thread.

(3) the demise of the JVM instance: JVM exits when all non-daemon threads in the program terminate; if the security manager allows, the program can also use the Runtime class or System.exit () to exit.

The life of the class

The complete life cycle of a java class goes through five stages: loading, connecting, initializing, using, and unloading. Of course, there are also cases where it is used directly without being initialized after loading or connecting.

The parent delegation model is a specification for organizing the relationship between class loaders. Its working principle is that if a class loader receives a request for class loading, it will not attempt to load the class itself. Instead, it delegates the request to the parent class loader to complete, so that all load requests are eventually passed to the top-level startup class loader. Only when the parent class loader cannot complete the load request (the desired class is not found in its search scope) will it be handed over to the subclass loader to attempt to load.

Recognize the JVM memory model

For JVM memory, programmers only need to pay attention to

Where does the object go-heap memory (including the new generation and the old era, which is divided into Enden area and two Survivor areas), heap memory is used to store objects, reasonable partitioning is mainly to improve the efficiency of garbage collection, the newly created objects will be in the Enden area, and they will go to the Survivor area after Minor GC, and they will enter the old era if they survive 15 times of GC.

How functions are called-stack memory is used to run threads, which contain temporary data in the method and specific data referenced by other objects in the heap.

Where the class goes-the method area is used to store type information (runtime constants and static variables) and method code and constructor code, usually called permanent generation, which JDK8 uses metaspace instead of permanent generation

JVM resources are generally divided into two kinds of CPU and memory, CPU represents thread stack, memory represents heap, and often production environment JVM problems are generally caused by the lack of these two kinds of resources. When thread stack is not used properly, CPU is usually full, and memory overflow usually occurs when heap memory is not used properly.

Memory management cleaner-garbage collection

One of the biggest advantages of the Java programming language is automatic garbage collection. Java garbage collection finds useless objects, removes them from memory and releases memory for later created objects. The following picture vividly compares the difference between manual garbage collection and automatic garbage collection. Garbage collection focuses on fragmentation and performance.

Initial knowledge of garbage collection algorithm

By recycling strategy

(1)。 Reference counting algorithm:

Add a reference counter to the object, which increases the counter value by 1 whenever there is a reference; when the reference fails, the counter value is subtracted by 1; an object with a counter of 0 at any time is no longer used. The garbage collector will reclaim the memory used by the object. The reference counting algorithm is simple and efficient. Microsoft's COM technology, ActionScript, Python and so on all use the reference counting algorithm for memory management, but the reference counting algorithm is difficult to solve the problem of circular references between objects, so java does not use the reference counting algorithm.

(2)。 Root search algorithm:

Through a series of objects named "GC Root" as the starting point, search down from these nodes, the search path is called reference chain (Reference Chain). When an object is not connected to GC Root with any reference chain, the object is unreachable, the object is unusable, and the garbage collector will reclaim the memory it occupies.

In the Java language, GC Roots objects that can be used as Java objects include the following:

A.System Class, like java.util.* in rt.jar

B.Thread, the thread that starts the state

c. Objects referenced in the virtual machine stack (local variables in the stack frame)

d. Objects referenced by static properties of a class in the method area

e. Objects referenced by constants in the method area

f. Objects referenced by JNI in the local method stack

(3)。 Tag-clear algorithm:

The most basic garbage collection algorithm is divided into two stages: "marking" and "clearing": first, all the objects that need to be recycled are marked, and all the marked objects are recycled uniformly after the marking is completed.

There are two disadvantages of the mark-removal algorithm: first, the efficiency problem, marking and cleaning efficiency are not high. Secondly, a large number of discontiguous memory fragments will be generated after tag removal, and too much space debris will cause programs to find enough continuous memory when they need to allocate memory for larger objects and have to trigger another garbage collection action in advance.

(4)。 Replication algorithm:

Divide the available memory into two equal blocks of capacity, and use only one of them at a time. When this piece of memory is used up, copy the surviving objects to another piece of memory, and then clean up the used memory space at once. In this way, one of the pieces of memory is reclaimed every time, and the complex situations such as memory fragments do not need to be taken into account when allocating memory. It only needs to move the pointer at the top of the stack and allocate memory sequentially, which is simple and efficient.

The disadvantage of the replication algorithm is obvious, reducing the available memory to half of the original.

(5)。 Mark-clear-organize algorithm:

The tag-collation algorithm is improved on the basis of the tag-removal algorithm. In the marking phase, all the objects that need to be recycled are marked out in the same stage. Instead of cleaning up the recyclable objects directly after the completion of the marking, all the surviving objects are moved to one end, and the recyclable objects are cleared in the process of movement. This process is called sorting.

The advantage of the mark-demarcation algorithm over the mark-cleanup algorithm is that it will not cause a large number of discontiguous memory fragmentation problems after the memory is demarcated.

The replication algorithm will perform more replication operations in the case of high object survival rate, and the efficiency will become lower, while in the case of high object survival rate, the efficiency of using marking-finishing algorithm will be greatly improved.

Reclaim by partition

(1)。 Generation algorithm:

The memory is divided into several blocks according to the survival cycle of the object. Generally, the java heap is divided into the new generation and the old age, so that the most appropriate collection algorithm can be adopted according to the characteristics of each age. In the new generation, each garbage collection found that a large number of objects died, only a small number of survival, then choose the replication algorithm, only need to pay a small amount of replication cost of surviving objects to complete the collection. In the old days, because the survival rate of the object was high and there was no extra space to allocate guarantee to him, it was necessary to use the "mark-organize" algorithm for recycling.

By system thread

Serial / parallel recycling mode: in the GC process, the single-thread / multi-thread collector adopts Stop-the-World mechanism and has high throughput.

Concurrent collection: worker thread and garbage collection thread execute concurrently, with low throughput, but ensure that other user threads can work during GC.

Garbage collector

Common parameters of JVM

Finally, summarize the common configurations of JVM

Class loading Settings

-XX:+TraceClassLoading: class load log

-XX:+TraceClassUnloading: class unload log

Heap settings

-Xms: initial heap size

-Xmx: maximum heap size

-XX:NewSize=n: sets the size of the younger generation

-XX:NewRatio=n: sets the ratio of the younger generation to the older generation. For example, 3 means that the ratio of the young generation to the old generation is 1:3, and the young generation accounts for 1% of the sum of the young generation and the old generation.

-XX:SurvivorRatio=n: the ratio of Eden region to two Survivor regions in the young generation. Notice that there are two in the Survivor area. For example: 3, which means Eden:Survivor=3:2, and one Survivor area accounts for 1x5 of the whole younger generation.

-XX:MaxPermSize=n: sets the persistent generation size

Collector Settings

-XX:+UseSerialGC: set the serial collector

-XX:+UseParallelGC: sets the parallel collector

-XX:+UseParalledlOldGC: set parallel older generation collection

-XX:+UseConcMarkSweepGC: sets the concurrent collector

Garbage collection statistics

-XX:+PrintGC

-XX:+PrintGCDetails

-XX:+PrintGCTimeStamps

-Xloggc:filename

Parallel Collector Settings

-XX:ParallelGCThreads=n: sets the number of CPU to use when collecting by the parallel collector. Number of threads collected in parallel.

-XX:MaxGCPauseMillis=n: sets the maximum pause time for parallel collection

-XX:GCTimeRatio=n: sets the percentage of garbage collection time to program running time. The formula is 1 / (1cm n)

Concurrent Collector Settings

-XX:+CMSIncrementalMode: set to incremental mode. Suitable for single CPU situations

-XX:ParallelGCThreads=n: the number of CPU used when the young generation of the concurrent collector is collected in parallel. Number of threads collected in parallel.

The above is all the content of this article "sample Analysis of JVM". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report