Understanding JVM virtual machine

What is the JVM

Is an abbreviation JVM Java Virtual Machine (Java virtual machine), JVM is a specification for A computing device, which is a fictional computer, is passed over the actual computer simulation of various computer-implemented functions.
After the introduction of Java virtual machine language, Java language does not need to be recompiled to run on different platforms when. Java Virtual Machine using Java language information associated with a particular shielding platform, so that only Java language compiler to generate object code (bytecode) running in the Java virtual machine can run without modification on multiple platforms .

Structure of the Java Virtual Machine

Here Insert Picture Description
This picture reference JVM configuration diagram of widely circulated online.

Run-time data area

Various runtime data area during program execution. Some of the data area is created when the Java virtual machine is started, be destroyed only when the Java Virtual Machine exits, such as the method area , heap area data area. Other area private threads, each data area is destroyed when the thread exits, such as PC program counter , the virtual machine stack , native method stacks .

PC Program Counter

Each CPU has a program counter PC i.e. register, the program counter PC records the current thread bytecode instructions executed address, often called the line number indicator.
When the bytecode interpreter work, the bytecode instructions is selected by changing the value of the program counter is a need to perform a branch, jump, loop, exception handling and other basic functions needed to accomplish this counter.
Java is a language support multi-threaded, multi-threaded so-called reality is achieved by the CPU round-robin scheduling algorithm, within a time slice, the processor instruction only one thread of execution.
In order to ensure the implementation can be restored to its original position when the thread switching process, each thread will have a separate program counter (ie thread private), without prejudice to each other between the various threads, isolated storage
program counter is the only one specification in the Java Virtual Machine It does not provide for any area of memory overflow condition.

Java Virtual Machine stack

Virtual machine stack Java memory model described method performed while performing the method creates a stack frame for the local variable table storage method, the operand stack, dynamic connection information like outlet method, each method execution is completed from the calling know, it corresponds to a stack frame to push the stack in a virtual machine process stack.

stack

Each thread shared memory region, class instances and arrays of memory allocated on the heap, the heap is created when the virtual machine starts.

Methods district

Storage structure of each class, e.g. runtime constant pool, field and method for static data, and methods and constructors code, including the special methods for instantiating classes and interfaces and initialization, runtime constant pool area allocation method also RAM

Runtime constant pool

And for storing various literal reference symbol generated by the compiler, this part will enter the methods of classes loaded area.

Native method stacks

Java Virtual Machine stack effect is similar, the difference lies in their virtual machine execution stack for the Java virtual machine service method, and native method stacks, the virtual machine to use a method of Native service. Use of the native method stacks in a virtual machine language specification, and the way the data structure is not mandatory, so the specific virtual machine it may be implemented. Some virtual machines directly to the native method stacks and stack virtual machines combined.

Parent delegation model

If a class loader loads the class received a request, it does not own to load this class, but to delegate this request to the parent class loader to complete, and only when the parent class loader loads the request could not be completed, the child class loader will attempt to load the class.

Here Insert Picture Description

Class loader

Start class loader : Bootstrap ClassLoader, it is part of a virtual machine, used to load core libraries. Java_HOME / lib / directory, or by -Xbootclasspath path specified by the parameter and the virtual machine is identified library
extension class loader : Extension ClassLoader, Java extension library is responsible for loading. All libraries loading / lib / ext directory or system variable Java.ext.dirs specified path.
Application class loader : Application ClassLoader, is responsible for loading the specified library on the user's classpath classpath, we can directly use this class loader. Normally we do not have custom class loaders default is to use the loader.

Class life cycle

Classes are loaded into the virtual machine memory began to unload a far memory, in fact, his entire life cycle includes seven stages.
Loading, validation, preparation, parsing, initialization, use and uninstall.
In which the load, validation, preparation, initialization and parsing five stages are sequential, and analytical might not be.

Loading the class

Class is the first five stages of the life cycle of Here Insert Picture Description
loading virtual machine needs to be done about the three things
(1) to get such a binary byte stream (from a Class does not specify file permissions acquired by naming a class, from other channels, such as: network, dynamically generated, databases, etc.)
(2) this static storage structure represented by the byte stream into a data structure region runtime method
(3) in the memory (for the purposes of that method HotSpot VM region ) generates a representative java.lang.Class object of this class, as a method to access the various data entry areas of this class
verification generally be required to complete the inspection of the operation of four stages
(1) file format validation: verify whether the byte stream with Class file format specification (version number is within a range of virtual machine processing, whether there is the constant in the constant pool types are not supported)
(2) verification of metadata: information described bytecode semantic analysis to ensure compliance with the information described in Java language specification requirements (eg: if there parent class, except java.lang.Object); (.
3) Bytecode verification: the data flow and control flow analysis to determine the semantics of the program is legitimate, logical;
(4) verification of symbolic references: to ensure that the analysis operation can be performed correctly.
Validation phase is very important, but not necessarily, has no effect on the program run. If the referenced class after repeated verification, consider using -Xverifynone parameter to shut down most of the class verification measures to shorten the time the virtual machine class load.
readyPreparation phase is formally allocate memory and set the stage class variable initial value of a class variable (static member variables), the memory used by these variables are allocated in the method area. This time includes only the memory allocation class variables, instance variables without including instance variables of an object instance will be assigned along with the objects in the heap. Secondly, here the initial value "Normally" is the data type of zero value, assuming a class variables are defined as follows

	那么,变量在准备阶段过后的值还是0,而不是111.因为这时候没有开始执行任何Java方法,而把value赋值为
	111的putstatic指令是程序被编译后,存放于类构造器方法<clint>()之中,所以把value赋值为111的动作将在初始化阶段才会执行。
    public static int value=111;
    特殊情况:当类字段的字段属性是ConstantValue时,会在准备阶段初始化为指定值,所以标注为final之后,value在准备阶段初始值为111而不是0
    public static final int value=111;

Parsing
parsing stage is a process of constant pool of virtual machines will replace symbolic reference directly referenced. The main analysis operation on the class or interface, field, class methods, the interface method, the method type, and method invocation handler class symbol reference point 7 qualifiers.
Initialization
initialization phase is the final step class loading process. In front of the class loading process, in addition to the Java program in the loading phase of the user application can outside the custom class loader to participate in the remaining action is entirely virtual machines dominate and control, to the initialization phase, began in earnest the implementation of the class defined the code (bytecode).
In the preparation stage variables that have been assigned over the initial value (zero value) once the system requirements; while in the initialization phase, to initialize class variables and other resources according to the procedures specified in subjective plan, or, more bluntly: the initial stage of the implementation of the class process constructor () method. () Method is implemented by the assignment operation compiler automatically collected class all class variables and static statement block static statements merger of {}, the order compiler collection was in order of appearance by the statement in the source file of the decision static statements can only block access to static variables defined in a block of statements before, the definition of variables behind it, can be assigned a static statement in front of the block, but can not access.

    int a=0;
    static {
    	a是对象创建之后才分配内存在堆上。
        a;//Non-static field 'a' cannot be referenced from a static context
    }

Here Insert Picture Description

Creating objects

Using new constructor is called
using newinstance method calls the constructor of the Class
using newInstance method Constructor class calls the constructor
cloning an object (shallow clone, deep clone) using the clone method
using deserialization?

JVM garbage collection mechanism

In Java, the programmer does not need to release the memory of a display object, but performed automatically by the virtual machine. In the JVM, there is a garbage collector thread, it is a low priority, under normal circumstances will not be implemented only when the virtual machine is idle or the current lack of heap memory, will trigger the execution of the scan are not any references to those It objects, and add them to the collection recovered, recovered

Garbage collection algorithm

Reference counting
Here Insert Picture Description
can be seen that the circular reference JVM not be recovered.
Reachability analysis the GC Root
(. 1) referenced target virtual machine stack (local variable stack frame of the table);
objects (2) Method zone class static attribute reference; and
(3) a constant region of object methods cited ;
(4) local stack referenced object.Here Insert Picture Description

Recovery strategy / algorithm

Mark - sweep
the first mark, then clear, there will be many after clearing space debris, if the latter need to allocate large objects, will lead to no contiguous memory available
mark - finishing
first mark, then clear finishing, solved space debris The problem. Then there was a new problem, each had to move objects.
Replication algorithm
the designated memory space into two equal regions, each region using only one. When garbage collection, traversing the region of the current used to copy live objects to another area, the last target area recyclable using current recycling.

Generational collection
based on the survival period of the object memory is divided into a few pieces. Generally including the young generation. Years old and permanent generations,

The garbage collector

Java provides three different scenarios according to the type of the collector, are serial, throughput and user response time priority Priority
Here Insert Picture Description

CMS (concurrent GC) Collector

Throughout the collection process is roughly divided into four steps
(1) initial labels
(2) concurrent mark
(3) re-mark
(4) concurrent clear
where initial labels, these two steps need to re-mark user pauses other threads. CMS is due to the use of the mark - sweep algorithm, it will still produce a lot of debris, space debris when too much, it will bring a lot of trouble to assign objects, such as allocation of large objects, the memory space can not find contiguous space to allocate not Full GC is not a departure in advance, in order to solve this problem, CMS collector provides a -XX: UseCMSCompactAtFullCollection parameters
for re-Full GC increase after a defragmentation process, but also through -XX: CMSFullGCBeforeCompaction parameter is set to perform many times uncompressed after the Full GC, followed by a defragmentation process.

G1 collector (user response time priority)

(1) concurrently and in parallel:
(2) a generational collector
(3) Spatial Integration
(4) to predict the stall Here Insert Picture Description
G1 concepts also exist's internal similar checkered one region composition
region introduced
the same size, the value is from 1M to power stop tree between a 32M bytes 2, JVM 2048 will try to divide the left and right, region of the same size. This number can be adjusted manually, G1 will be automatically adjusted according to the size of the heap.
G1 implementation, as part of Eden region, as part of Survivor, part of Old, G1 region50% will exceed the size of the target object is classified as Humongous, and placed in the appropriate region. Logically, Humongous region regarded as a part of old age, such as copying large object is very expensive operation, not suitable for the new generation of GC replication algorithm.

Shortcomings G1.
region size and large objects is difficult to ensure consistency, which can lead to waste of space; particularly large objects is likely to occupy more than one region of. And, region too inappropriate, you will make it more difficult to find contiguous space in the allocation of a large object, which is the case of a long-term existence.

Angle GC algorithm, G1 choice is complex algorithms that can simplify understood as follows:
In the new generation, G1 is still used copy of parallel algorithms, so the same Stop-The-World of the pause will occur. Clean-up of the new generation will bring good old zone has been marked region.
Are concurrent mark under the old era, in most cases, and finishing (Compact) is carried out and the new generation of the GC incidentally, and not the integrity of finishing, but increments, that is, the new generation of the original area object when sufficiently old, which can be directly into the old generation area.

Humongous object allocation and deallocation
Humongous region as a part of old age, usually thought it would be recovered after the end of the concurrent mark, but in the new version of the G1, the object Humongous recovery has taken a more aggressive strategy. We know that the object reference G1 recorded between old's region, Humongous limited number of objects, it is possible to quickly know if there's the old object reference to it. If not, it may be able to prevent the only recovery, if there is a new generation of object references to it, but this information is to know when Young GC, so it can be recycled Humongous objects in Young GC in, do not like other years old objects as concurrent mark the end of the wait.

Virtual machine performance monitoring

VM process status tool -jps : virtual machines can list running processes.
Display virtual machine executes the main class name and local processes these virtual machines unique ID.
Virtual Machine statistics monitoring tools -jstat : command tool to monitor virtual machines for various operating status information.
Display virtual machine class loading, memory, garbage collection, JIT compiler and other operating data
Java memory imaging tools -jmap : for survival heap dump snapshots
can also query execution queue finalize details Java heap and permanent generations.
Such as space usage, current collectors used
Java stack trace tool -jstack : thread virtual machine snapshots to survive the current time
Java monitoring and management of the public too -JConsole : visual monitoring, management tools
can see all the information about the JVM, including memory, thread , class, VM and GC summary information

JVM tuning ideas

View stack information to determine whether the space is too small heap
View Full GC circumstances to determine whether a memory leak
to use reasonable garbage collector
heap space minimum memory and maximum memory is set to the same there will be expansion and contraction capacity of the case

Examples JVM common parameters

Memory Settings

Parameter Meaning
initial heap size -Xms1024m
-Xmx1024m maximum heap size
-Xmn500m CENOZOIC size
-Xss1024K single thread stack
-XX: PermSize = 200m substituting permanent Java8 before
-XX: MaxPermSize = 300m Java8 permanent substituting berfore
-XX: MetaSpaceSize metadata after 8
-XX: MaxMetaSpaceSize metadata. 8 After
-XX: NewRatio. 4 Olden area ratio = area Young. 4:. 1
-XX: =. 8 SurvivorRatio Eden area ratio S region. 8:. 1:. 1
-XX: optimizing the memory page size JVM LargePageSizeInBytes National Cheng Kung University paging tone

GC settings

新生代(别名) 老年代 JVM参数
Serial (DefNew) Serial Old(PSOldGen) -XX:+UseSerialGC
Parallel Scavenge (PSYoungGen) Serial Old(PSOldGen) -XX:+UseParallelGC
Parallel Scavenge (PSYoungGen) Parallel Old (ParOldGen) -XX:+UseParallelOldGC
ParNew (ParNew) Serial Old(PSOldGen) -XX:-UseParNewGC
ParNew (ParNew) CMS+Serial Old(PSOldGen) -XX:+UseConcMarkSweepGC
G1 G1 -XX:+UseG1GC

Debugging parameters

Parameter Meaning Description
-XX: + PrintGCDetails GC log
-XX: + PrintGCApplicationStoppedTime GC pauses
-verbose: gc / class / jni View gc, class loading, the native method call
-XX: + PrintHeapAtGC printing stack during GC triggered
-Xloggc: log /gc.log log output GC
-XX: + HeapDumpOnOutOfMemoryError generated when dump heap memory overflow
-XX: + HeapDumpOnCtrlBreak Crtl + Break generated dump

Published 24 original articles · won praise 1 · views 531

Guess you like

Origin blog.csdn.net/qq_45366515/article/details/105045804