Detailed java virtual machine (the original source is indicated)

Disclaimer: This article is a blogger original article, follow the CC 4.0 by-sa copyright agreement, reproduced, please attach the original source link and this statement.
This link: https: //blog.csdn.net/qq_31142553/article/details/81603539


First, walked into Java
Java technology system includes a virtual machine, Java API, Java programming language, a third-party Java frameworks.

In the virtual machine level hides the complexity and diversity of the underlying machine and operating system technology.

Java programming language, Java virtual machine, Java API class libraries collectively referred to as JDK.

Two, Java area of memory and memory overflow exception
data area of the Java runtime
threads share: Method district, heap

Thread isolation: Virtual machine stack, native method stacks, program counter

The program counter is the current thread bytecode executed by the line number counter, multithreaded JVM is alternately switched by a thread and allocation of processor execution time to achieve.

Java virtual machine stacks the life cycle of the same thread, each method will be executed at the same time create a stack frame for storing local variable table, the operand stack, dynamic links, and other information for export, every method call until the completion of the execution process, it corresponds to a stack frame to push the stack in a virtual machine process stack. Local variable table stores all the basic data types known to the compiler, and returnAddress object reference type, the required memory allocation is completed at compile time and will not change during operation of the method. If the stack is greater than the depth of the thread requested virtual machine allowable depth, StackOverFlowError will throw an exception; if the virtual machine can dynamically expand the stack, can not be extended to apply if enough memory, an exception will be thrown OutOfMemeryError.

Native method stacks and stacks similar to the virtual machine, is to use the native method jvm service, and some such as Sun HotSpot virtual machine into one of them.

Java heap is shared by all threads in an area of ​​memory, it is the largest piece of memory jvm management, created when the virtual machine starts. Almost all object instances and arrays must allocate memory in the heap. Java heap is the main area managed by the garbage collector can be divided into the old and the new generation's, the more specific the points system is Eden space, From Survivor space, To Survivor space. If not enough memory to complete the heap allocation instance, and the stack can no longer expand, it will throw an OutOfMemoryError.

A method for storing class information area of ​​the virtual machine has been loaded, a constant, static variables, the compiler code, etc. immediate data, is described as a logical part of the stack, referred to as non-stack, essentially no generation of equivalence permanent . (JDK8 change)

Runtime constant pool is part of the zone method. Class file versions in addition to the classes, fields, methods, and interface description information, as well as a constant pool information, and for storing various literal reference symbol generated by the compiler, this part will load the class the method of entering the zone runtime constant pool of storage, during operation may be the new constants into the pool, such as the intern method of the String class.

Direct memory, external memory heap allocation, e.g. NIO.

Objects created: positioning parameters, allocating memory (pointer collision, the free list), the initialization value of zero, init.

Memory layout objects: object header, instance data, alignment padding.

-Xms minimum and maximum parameter memory -Xmx parameter set will automatically extend as to avoid stack.

Parameter -XX: + HeapDumpOnOutOfMemoryError allows virtual machines in the event of memory overflow Dump the current snapshot of the heap dumps for post-mortem analysis.

Memory leak: objects need to be recovered should not be recovered

Third, the garbage collector and memory allocation strategy
more details, please see: https: //blog.csdn.net/qq_31142553/article/details/81295331

Program counter, stack virtual machine, native method stacks with three regions born threads, with threads off; stack as the stack frame of the method of entry and exit in an orderly manner and stack pop operations; each stack frame how much memory is allocated when the class structure is substantially known per finalized.

Reference counting algorithm: It is difficult to solve the problem of mutual circulation between object references.

Reachability analysis algorithm: when an object is not connected to any reference GC Roots chain, showing that the object is not available.

As GC Roots object has: the target virtual machine stack (Local Variable Table stack frame) referenced process zone class object static attribute references, an object method area constant references, native method stacks in the JNI (i.e. in general the Native method) object references.

References cited into strong, soft, weak, reference phantom reference.

District recovery methods: virtual machine implementations may not be required in the method of garbage collection area.

Analyzing type of unnecessary conditions: 1, all instances of the class have been recovered, i.e. Java heap any instance of the class does not exist. 2, the class loading ClassLoader has been recovered. 3, corresponding to the class Java.lang.Class object is not referenced anywhere, not reflected by the method of accessing the class at any place, also need jvm parameters to control is turned on.

Mark - sweep algorithms: mark and sweep efficiency is not high; a large number of discrete memory chips after clearly marked.

Replication algorithm: a larger piece of Eden and two small Suivivor.

Mark - Collation Algorithm: Surviving moved to the side to clean up the other side.

Generational collection algorithm: Depending on whom the survival period of the memory is divided into a few pieces, such as the new generation and the old era.

In the implementation of the HotSpot, using a set of data structure to hold OopMap what a place to store the object reference.

Serial Collector: single-threaded, stop all execution.

ParNew collectors: Serial version is multi-threaded version, it currently only works with the CMS collector.

Parallel Old Collector: Throughput priority.

Serial Old Collector:

Parallel Old Collector:

CMS collector: to obtain the minimum collection pause time of the target, the step comprising an initial flag, concurrent mark, re-marking, concurrent recovery, concurrent collection, low pause shortcomings 1, CPU resources sensitive; 2, can not handle the floating garbage; 3, a large amount of space debris.

GI collector: JDK7, replace the CMS, advantages of parallel and concurrent, generational collection, Spatial Integration, predictable pause, comprises an initial mark, concurrent mark, the final mark, screening recovery, operation log, the GC log, the thread snapshot ( threaddump / javacore file), the problem of positioning data dump heap snapshot (heapdump / hprof file), exception stack and so on.

Fourth, the virtual machine performance monitoring and troubleshooting tool
jdk command-line tool

jps: VM process status tool

jstat: Virtual Machine Statistics Monitoring Tool

jinfo: Java configuration tool

jmap: Java Memory mapping tool

jhat: a snapshot of the virtual machine heap dump analysis tool

jstack: Java stack trace tool, Thread.getAllStackTraces

HSDIS: jit generate code decompilation

Jdk of visualization tools

JConsole: Java Monitoring and Management Console

VisualVM: in-one troubleshooting tool

Fifth, the class file structure
businesses and institutions have developed open-source Java language in addition to a large number of languages running on the Java virtual machine, such as Clojure, Groovy, JRuby, Jython, Scala and so on.

Any confrontation with a Class file definition information only class or interface.

A plurality of tables are unsigned number or other complex data types as a table configuration of the data item.

High-energy version of the jdk backward compatible with previous versions of Class files, but can not run later versions of Class files even formatting intact.

The constant pool can be understood as a warehouse of resources among the Class file, which is the most data types Class file structure associated with other projects.

Class file byte code analysis tools are: javap.

Bytecode instructions: bytecode data type, load and store instructions, arithmetic instructions, the type of conversion instruction, and accessing the object creation instruction, the operand stack management instruction, branch instruction, the method call and return instructions, exception processing instructions, synchronization instructions.

Sixth, VM class loading mechanism
in Java can dynamically expand natural language feature is dependent on the run dynamic loading and dynamic linking This feature implementation.

Lifecycle class: loading, validation, preparation, parsing, initialization, use and uninstall. Wherein the verification, preparation, referred to as analytical portion 3 is connected. Loading, validation, preparation, initialization sequence and unload these five stages are determined.

Class initialization trigger conditions:

1, encounter new, getstatic, putstatic, invokestatic which four instructions and classes not been initialized.

2, java.lang.reflect package using a method based on the reflecting type calls and when not been initialized.

3, before initializing a class, the first trigger initialization of the parent class.

4, the main class starts the specified virtual machine to be executed to initialize.

5, when calling the dynamic language support jdk1.7, if a final example of the analysis result java.lang.invoke.MethodHandle REF-getStatic, REF-putStatic, REF-invokeStatic method handle, and this method handle class corresponding not been initialized, you need to trigger its initialization.

For static fields, only the direct definition of the class of this field will be initialized.

To refer to the class by the array definition, it does not trigger this type of initialization.

Constants at compile time will be credited to the constant pool class is called, there is no direct reference to the definition of the class constants of nature, it will not trigger initialization class defined constants.

When a class at initialization, requires all of its parent class has been initialized, but an interface at initialization, the interface does not require the parent completed the initialization, only (as cited in real time using a parent interface to interface defined constants) will be initialized.

Class loading process

In the loading phase to accomplish three things: 1, to obtain such a binary byte stream defined by the fully qualified name of a class; 2, this byte stream represents static storage structure into a region of the operating method data structure; 3, generating in memory represents java.lang.Class object of this class, as a method for accessing the various data entry areas of this class. Developers can define their own class loader to control the acquisition mode byte streams (i.e., a class loader override loadClass method).

Uniqueness of a class must be determined with the class loader.

Memory instantiated java.lang.Class objects stored on the heap is not clearly defined.

Part of the load phase and the connection phase for the cross, but the start time of the order remains fixed.

The purpose of the validation phase is to ensure that the information byte stream file included in Class meet the requirements of the current virtual machine and the virtual machine will not jeopardize their own safety.

Validation phase substantially complete check operation four stages: 1, check the file format, the magic number, for example, the version number; 2, metadata validation, e.g. subclass whether the final field covers the parent class; 3, bytecode verification , for example, to ensure that body type conversion method is effective; 4, reference symbol verification, to ensure that the analysis operation can be performed normally.

Preparation phase is the official allocate memory for the class variables and class variables set the initial phase value, these variables are used in the memory area allocated in the process.

In the instance variables will be allocated when the object is instantiated in Java heap along with the object.

The initial value is usually zero value, the value will be set during the initialization phase specified. However, the constants (static final) initialization value is set to a value of the specified property.

 Parsing stage is a virtual machine to a constant pool of symbolic references to the process of replacing direct references.

Symbol reference to a certain set of symbols described in the referenced, literal symbols may be in any form, can be positioned unambiguously as long as the goal to use.

A direct reference may be a direct pointer to the target, a relative offset or indirectly targeted to handle targets.

Performing anewarray, checkcast, getfield, getstatic, instanceof, invokedynamic, invokeinterface, invokespecial, invokestatic, invokevirtual, ldc, ldc_w, multianewarray, new, putfield putstatic and 16 for this bytecode instruction operation before the symbolic references, firstly reference symbols are used for analyzing.

Mainly for parsing class or interface, fields, methods class, interface method, type method, and calls the method handle 7 points class qualifiers for symbolic references.

 Constant type class methods and interface method reference symbols are separated, if it is found in the class method table of the class-index index c is an interface, it is thrown directly java.lang.IncompatibleClassChangeError exception.

java.lang.IllegalAccessError abnormalities usually access.

During the preparation phase, the variable has been assigned an initial value once the system requirements, and in the initialization phase, the plan is based on subjective procedures developed by programmers to initialize variables and other resources. Or during the execution of the initialization phase is a class constructor <clinit> () method.

<Clinit> () method is the assignment operation compiler automatically collected class all class variables and static block of statements (static {}) statements merger sequentially compiler collected appeared by the statement in the source file the order of the decision, the static statement block only access to the 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.

Virtual opportunity to ensure that before the subclass <clinit> () method executes, the parent class <clinit> () method has already been implemented.

Statically defined parent class statement block takes precedence subclass variable assignment.

<Clinit> () method for the class or interface is not necessary.

You can not use a static interface statement block only when the parent variables defined in the interface using parent interface will be initialized.

Virtual opportunity to ensure that a class <clinit> () method correctly locked in a multithreaded environment, synchronization.

Under the same class loader, a type initialization only once.

For any category, you need to load it established by the class loader and the class itself with its uniqueness in the Java virtual machine, each class loader has a separate class namespace.

Boot class loader Bootstrap ClassLoader: If no bootstrap class loader is used to place this null.

Extension class loader Extension ClassLoader.

Start class loader Application ClassLoader, also known as the system class loader is responsible for loading the user class path (ClassPath) on the specified library.

In addition to the parent delegation model requires top-level boot loader class, the rest of the class loader should have its own parent class loader.

Parent delegation model is working process: If a class loader loads the class received a request, it first does not own to try to load this class, but to delegate this request to the parent class loader to complete each level of the class loader is true, so all requests ultimate load should be transferred to the top of the boot class loader, only when the parent class loader to load the feedback they can not complete the request (in its search did not find the desired category) when the sub-loader will try to load your own.

Stack frames are used to support virtual machine data structures and methods for performing the method calls, which is a virtual machine runtime data area of ​​virtual machine stack stack elements.

Storing a local variable stack frame methodology, the operand stack, and a method for dynamic link return address and other information.

Seven, virtual machine bytecode execution engine
local variable table is a set of variable values storage for storing local variables inside method parameters and method definitions. When a Java program thinking that Class file, to determine the maximum capacity of the local variables of the method required allocation table in max_locals data item code attribute method.

Objects should not be used to manually assign null: take up a lot of memory and the variable is no longer used, contributing to the timely GC. From a coding point of view, in the proper scope of the variable to control the variable time is the most elegant solution for recycling.

Method performed at any time, the depth of the operand stack will not exceed the maximum value set in max_locals data items.

Each stack frame contains a reference to the runtime constant pool of the stack frame associated method of holding the reference is to support the process of dynamic linking method call.

After the method is performed in two ways to exit this process is first performed in any engine encounters a bytecode instruction method returns, called normal completion outlet; the other is not encountered exception process is called abnormal completion exports.

Method call is not equivalent to the implementation of the method, the only task is to determine the method call stage version called method (that is, which method call), is not yet involved in specific operational processes within the method.

Written in the program code to call the target, must be finalized when the set of compiler, such methods called parsing call: the compiler found, run immutable, including methods and private static methods, instance constructors, parent method, final approach.

At compile time, Javac compiler will decide which overloaded version to use based on the static type of the parameter.

Overloaded priority variable-length argument is the lowest.

All rely on static type version of the method performed to locate the dispatch operation is called static allocation, a typical application of method overloading.

Dynamic dispatch and rewrite have a very close relationship.

 Only the object is determined to talk about some specific version of Java implementation and execution engine running mode, talk interpreted or compiled executables will be more precise.

 

 Java compiler program code After completion lexical analysis, syntax analysis to the abstract syntax tree, and then generates a syntax tree traversal linear bytecode instruction stream.

Java compiler output instruction stream, is essentially a set of instructions based on the stack frame, most of the instruction address of the instruction stream zero command.

Eight other
after JDK1.6 provides Compiler API, you can dynamically compile Java programs.

Compilation process can be roughly divided into three processes:

1, symbol table parsing the filling process.

2, the annotation plug-in annotation process processors.

3, bytecode analysis and generation process.

Lexical analysis of the source code is a character stream into a set of markers, a single character is the smallest element of the process of preparing the program, the flag is the smallest element of the compilation process.

Keywords, variable names, literals, operators can become a mark.

At runtime, the virtual machine to the hot code is compiled into machine code associated with the native platform, and various levels of optimization, this task is called a compiler-time compiler JIT.

Escape analysis of the basic behavior of the object is to analyze dynamic scope: Method escape and thread escape.

Optimization variables: the stack distribution, elimination of synchronization, scalar replacement.

Per transaction processed TPS, the total number of requests on behalf of one second server in response to the average energy.

volatile: 1, to ensure the visibility of the variable for all threads; 2, disable command reordering.

Two other keywords to achieve visibility: synchronized and final.

can achieve synchronized atoms, visibility, orderly.

When multiple threads access an object, if not consider alternate scheduling and execution under the environment of these threads at runtime and does not require additional synchronization, or perform any other operation in coordination caller, calling the object's behavior can be get the right result, that this object is thread safe.

 Thread-safe implementation:

1, synchronized mutually exclusive

synchronized keyword.

ReentrantLock advanced features: interruptible wait, can achieve a fair lock, the lock can bind multiple conditions.

2, non-blocking synchronization: CAS (compare and swap)

3, no synchronization scheme: reentrant code thread local storage

Guess you like

Origin www.cnblogs.com/liveinpresent/p/11360171.html