Detailed introduction to the Java Virtual Machine (JVM)

Source: Internet
Author: User
Tags xms

1. JVM Life cycle
    • Start. When a Java program is started, a JVM instance is generated, and any class that has the public static void main (string[] args) function can be used as a starting point for the JVM instance to run.
    • Run. Main () is the starting point for the program's initial thread, and any other thread is started by that thread.
    • Die. The JVM exits when all non-daemon threads in the program terminate, and the program can use the runtime class or System.exit () to exit if the security Manager allows it.

A running Java Virtual machine has a clear task: Executing a java program. He runs when the program starts, and he stops at the end of the program. You run three programs on the same machine and there are three running Java virtual machines. The Java Virtual machine always starts with a main () method, which must be public, return void, and be directly affected by an array of strings. When the program executes, you must indicate to the Java Virtual machine the class name of the replacement main () method. The main () method is the beginning of the program, and the thread that he is executing is initialized to the program's initial thread. The other threads in the program are started by him.

There are two types of threads in Java: The daemon thread (daemon) and the normal thread (Non-daemon). A daemon thread is a thread that the Java virtual machine uses itself, such as a thread that is responsible for garbage collection, which is a daemon thread. Of course, you can also set your own program as the daemon thread. The initial thread that contains the main () method is not a daemon thread.

As long as there are normal threads executing in the Java virtual machine, the Java Virtual machine will not stop. If you have sufficient permissions, you can call the exit () method to terminate the program.

2. JVM Architecture

1) class loader (ClassLoader) (Used to load. class files)

2) execution engine (byte code execution, or local method execution)

3) Runtime data area (method area, Heap, Java stack, PC register, local method stack)

3. JVM Runtime Data area

3.1 java Heap (heap)
    • A chunk of memory that is shared by all threads, created when the virtual machine is started
    • Used to store object instances
    • The size of the heap can be controlled by-XMX and-XMS
    • OutOfMemoryError exception: When there is no memory in the heap to complete the instance assignment, and the heap can no longer be expanded.

The Java heap is the primary area of garbage collector management. Java heap can also be subdivided into: Cenozoic (New/young), Old generation/aging (old/tenured). The Persistence generation (Permanent) is in the method area and does not belong to the heap.

Cenozoic: new objects are allocated memory by the Cenozoic. are often divided into the Eden and survivor areas. When Eden is out of space, it transfers the surviving objects to survivor. The Cenozoic size can be controlled by-xmn, and-xx:survivorratio can also be used to control the proportions of Eden and survivor.

old generation: stores objects that are still alive after multiple garbage collection.

Persistent generation: Store static files, Java classes, methods, etc. today. Persistent generation in the method area has no significant impact on garbage collection.

3.2 Method Area
    • Sharing between threads
    • Used to store data such as class information, constants, static variables, immediate compiler-compiled code, etc. loaded by the virtual machine
    • OutOfMemoryError exception: When the method area does not meet the allocation requirements for memory
    • Run a constant-rate pool
      • Part of the method area
      • A variety of literal and symbolic references, such as string-type constants, that are used to generate the compile-time generation of the store
      • OutOfMemoryError exception: When a constant pool is no longer available for memory
3.3 Java Virtual machine stack (VM stack)
    • Thread private, life cycle is the same as thread
    • Stores the local variable table ( basic type , object reference), operand stack, dynamic link, method exit, and other information of the method.
    • The Java method executes the memory model, each method executes simultaneously creates a stack frame, each method is called until completes the process, corresponds to a stack frame in the virtual machine stack from the stack to the stack process.
    • Stackoverflowerror exception: The stack depth requested by the thread is greater than the allowed depth of the virtual machine
    • OutOfMemoryError exception: Unable to request sufficient memory if the stack is extended

The JVM stack is thread-private, and each thread creates a JVM stack that is stored in the JVM stack as a variable of the local base type in the current thread, a partial return result, and a stack Frame. Objects of other reference types only hold variable names on the JVM stack and point to the first address of an object instance on the heap.

3.4 Local Method Stack (Native)
    • Similar to virtual machine stack, the native method service is mainly used by virtual machine, and the local method stack and virtual machine stack are directly in the hotspot virtual machine.
3.5 Procedure Counter (program Counter Register)
    • The line number indicator of the byte code executed by the current thread
    • Current thread Private
    • There will be no outofmemoryerror situation
3.6 Direct Memory
    • Direct memory is not part of the data area when the virtual machine is running, nor is it a memory area defined in the Java VM specification, but this part of memory is also used frequently

    • NiO can use the native library to directly allocate out-of-heap memory, and the Directbytebuffer object in the heap operates as a reference to this memory
    • Size is not limited by Java heap size and is subject to native (server) memory limitations
    • OutOfMemoryError exception: When system memory is low

  Summary: Java object instances are stored in the heap, constants are stored in a constant pool in the method area, and data such as virtual machine loaded class information, constants, static variables, instant compiler compiled code is placed in the method area, and the above zone is shared by all threads. The stack is thread-private, which holds the local variable table (basic type, object reference), operand stack, dynamic link, method exit and other information of the method.

A Java program corresponds to a JVM, and a method (thread) corresponds to a Java stack.

4. Compilation and execution of Java code

The compilation and execution of Java code includes three important mechanisms:

(1) Java source Code compilation mechanism (. Java code file,. class bytecode file)

(2) class loading mechanism (ClassLoader)

(3) class execution mechanism (JVM execution engine)

4.1 Java source Code compilation mechanism

Java source code is not recognized by the machine, the compiler needs to be compiled into a JVM can execute the. Class bytecode file, which is then interpreted by the interpreter to run. That is: Java source file (. java)--java compiler--Java bytecode file (. Class)--Java interpreter--execute. The flowchart is as follows:

The bytecode file (. Class) is platform-Independent.

Characters in Java exist only in one form: Unicode. Character conversions occur at the JVM and Os Junction (Reader/writer).

The resulting class file is made up of the following sections:

    • Structure information. Includes the class file format version number and the number and size of each part of the information
    • Meta data. The information that corresponds to the declarations and constants in the Java source code. Contains class/inherited superclass/implemented interface declaration information, domain and method declaration information, and constant pool
    • Method information. Corresponds to the information in the Java source code for statements and expressions. Includes byte code, exception Processor table, evaluation stack and local variable size, type record of evaluation stack, debug symbol information

Class 4.2 Loading mechanism (ClassLoader)

A Java program is not an executable file, but consists of several separate class files. These class files are not loaded into memory all at once, but are progressively loaded according to the program.

The class loading of the JVM is done through ClassLoader and its subclasses, and the hierarchy and loading order of the classes can be described as follows:

(1) Bootstrap ClassLoader

    • Root ClassLoaderof the JVM, implemented by C + +
    • Loading Java's Core API: $JAVA The loading of all class files in Jre/lib/rt.jar in _home, which contains all the interfaces and implementations of the Java specification definition.
    • This classloader is initialized when the JVM is started

(2) Extension ClassLoader

    • Loading the Java Extension API (classes in Lib/ext)

(3) App ClassLoader

    • Load the class defined under the Classpath directory

(4) Custom ClassLoader

    • The ClassLoader that the application customizes according to its own needs, such as Tomcat and JBoss, will be implemented according to the Java EE specification itself ClassLoader

  

The load process checks to see if the class is loaded, the check order is bottom-up, and the custom ClassLoader to bootstrap ClassLoader-by-layer check, as long as a certain classloader is loaded as if the class has been loaded. Ensure that only all classloader of this class are loaded once. The order of loading is top-down, that is, the upper layer tries to load the class one at a level.

Parental delegation mechanism

The JVM defaults to the parental delegation mechanism when loading classes. In layman's words, when a particular class loader receives a request to load a class, it first delegates the load task to the parent class loader, which in turn recursively. If the parent class loader can complete the class load task, it returns successfully, but only if the parent ClassLoader cannot complete the load task.

Effect: 1) avoid repeated loading; 2) more secure. If you are not a parent delegate, then the user writes a Java.lang.Object class in their own classpath, there is no guarantee of the uniqueness of the object. So use parental delegation, even if you write it, but will never be loaded run.

Destroying parental delegation mechanisms

The parental delegation mechanism is not a mandatory constraint model, but a ClassLoader implementation method recommended by Java designers to developers.

The thread context ClassLoader , which can be set by the Setcontextclassloader () method of the Java.lang.Thread class, will inherit one from the parent thread if it is not set when the thread is created. If it is not set at the global scope of the application, then the ClassLoader is the Application class loader. Like JDBC, this is how it is used. This behavior is reversed using the loader, violating the general principles of the parent delegation model.

Class 4.3 execution mechanism

The execution of Java bytecode is done by the JVM execution engine, and the flowchart is as follows:

The JVM is a stack-based architecture that executes class bytecode. After the thread is created, the program counter (PC) and stack (stack) are generated, and the program counter holds the offset of the next instruction to be executed in the method, and the stack frames are stored in each stack frame, and each stack frame corresponds to each call of each method, and the stack frame has a local variable area and a stack of operands . A two-part, local variable area is used to store local variables and parameters in the method, and is used to store the intermediate results produced during the execution of the method in the operand stack.

Key execution techniques: Interpretation, instant compilation, adaptive optimization, chip-level direct execution

    • Explanation belongs to the first generation JVM,
    • JIT compilation is a second generation JVM,
    • Adaptive optimization (currently used by Sun's HOTSPOTJVM) draws on the experience of first-generation JVMs and second-generation JVMs in a combination of both

Begin to take a way to interpret execution of all code and monitor code execution. Start a background thread for those methods that are called frequently, compile it as local code, and optimize it. If the method is no longer used frequently, the compiled code is canceled, and it is still interpreted for execution.

5. JVM garbage Collection (GC)

the rationale of GC is that objects that are no longer referenced in memory are recycled, and the methods used in GC for recycling are called collectors. Garbage: An object that is no longer referenced.

Since the GC consumes some resources and time, Java, after analyzing the life-cycle characteristics of an object, collects the objects according to the new generation and generation of generations in order to shorten the GC's pauses to the application as much as possible.

    • The collection of new generation objects is called minor GC;
    • The collection of objects for the old generation is called full GC;
    • The GC for the active invocation of System.GC () in the program is full GC.

Java garbage collection is performed by a separate background thread GC, and Autorun does not require a display call. Even if JAVA.LANG.SYSTEM.GC () is invoked, the method will only alert the system to garbage collection, but the system will not necessarily respond and may be ignored.

Determine if a piece of memory space meets the recycling criteria:

(1) The object is given a null value and is not called again (obj = null;)

(2) The object is given a new value, that is, the memory space is reassigned (obj = new obj ();)

memory leaks: The program retains references to objects that are never used again. As a result, these objects are not recycled by GC, but they always occupy memory space and are useless. That is: 1) the object is accessible; 2) The object is useless. These two conditions are sufficient to determine a memory leak.

You should ensure that unwanted objects are unreachable, usually by setting the object field to null, or by removing the object from the container collection. A local variable is no longer used without a display set to NULL, because a reference to a local variable is automatically purged as the method exits.

reasons for memory leaks:1) global set; 2) cache; 3) ClassLoader

6. Memory Tuning

Tuning Purpose: to reduce the frequency of GC, especially the number of full GC, too many GC will consume a lot of system resources affecting throughput. Pay particular attention to the full GC, as it organizes the entire heap.

main means: JVM tuning primarily configures the JVM's parameters to increase the speed of garbage collection, and allocates the proportion of the heap memory portions reasonably.

Several scenarios and tuning strategies that lead to full GC:

    • Insufficient space for old generation
      When tuning the object in the new generation of GC as far as possible to be recycled , so that the object in the Cenozoic to survive for a period of time and do not create too large objects and arrays to avoid creating objects directly in the old generation
    • Persistent generation (pemanet Generation) Insufficient space
      Increase Perm Gen space to avoid too many static objects
    • The average size of a statistically obtained GC promoted to an old generation is greater than the remaining space of the old generation
      Control the proportions of the new generation and the old generation
    • System.GC () is displayed call
      Garbage collection should not be triggered manually, depending on the JVM's own mechanism

What happens if the heap memory scale is bad:

1) New generation set too small

First, the new generation of GC frequency is very frequent, increase the system consumption, the second is to cause large objects directly into the old generation, occupy the old generation of residual space, induce full GC

2) New generation set too large

First, the new generation has set up the General Assembly lead to the old generation too small (heap total), thus inducing full GC; second, the new generation of GC time-consuming significantly increased

In general, the new generation of the whole heap 1/3 more appropriate

3) Survivor set too small

Causes the object to reach the old generation directly from Eden, reducing the time to live in the Cenozoic

4) Survivor set too large

Causes Eden to be too small, increasing the GC frequency

In addition, the-xx:maxtenuringthreshold=n to control the generation of survival time, as far as possible to make objects in the new generation is recycled

The JVM provides two simple ways to set up GC policies :

1) Throughput priority

The JVM chooses the corresponding GC strategy and controls the size ratio of the Cenozoic and the old generation to achieve the throughput index. This value can be set by-xx:gctimeratio=n.

2) Pause time First

The JVM takes pause time as the indicator, chooses the corresponding GC strategy and controls the size ratio of the Cenozoic and the old generation, and tries to ensure that the application stop time caused by each GC is completed within the specified value range. This value can be set by-xx:maxgcpauseratio=n.

JVM Common Configuration

  1. Heap Settings
    • -XMS: initial Heap Size
    • -XMX: Maximum Heap Size
    • -xx:newsize=n: Setting the young generation size
    • -xx:newratio=n: Sets the ratio of the younger generation to the older generation. such as: 3, the ratio of the young generation and the old generation is 1:3, the young generation of the entire young generation of old generation and 1/4
    • -xx:survivorratio=n: The ratio of Eden in the young generation to the two survivor districts. Note that there are two survivor districts. such as: 3, indicating Eden:survivor=3:2, a Survivor area accounted for the entire young generation of 1/5
    • -xx:maxpermsize=n: Setting the persistent generation size
  2. Collector Settings
    • -XX:+USESERIALGC: Setting up the serial collector
    • -XX:+USEPARALLELGC: Setting up a parallel collector
    • -XX:+USEPARALLEDLOLDGC: Setting up a parallel old generation collector
    • -XX:+USECONCMARKSWEEPGC: Setting the concurrency Collector
  3. Garbage collection Statistics
    • -xx:+printgc
    • -xx:+printgcdetails
    • -xx:+printgctimestamps
    • -xloggc:filename
  4. Parallel collector settings
    • -xx:parallelgcthreads=n: Sets the number of CPUs to use when the parallel collector is collected. The number of parallel collection threads.
    • -xx:maxgcpausemillis=n: Set maximum pause time for parallel collection
    • -xx:gctimeratio=n: Sets the percentage of time that garbage collection takes to run the program. The formula is 1/(1+n)
  5. Concurrent collector Settings
    • -xx:+cmsincrementalmode: Set to incremental mode. Applies to single CPU conditions.
    • -xx:parallelgcthreads=n: Set the concurrency collector the number of CPUs used by the young generation collection method for parallel collection. The number of parallel collection threads.

Reference Links:

Http://www.open-open.com/lib/view/open1408453806147.html

Http://www.codeceo.com/article/jvm-memory-overflow.html

http://blog.csdn.net/cutesource/article/details/5907418

Detailed introduction to the Java Virtual Machine (JVM)

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.