Java Virtual Machine Detailed

Source: Internet
Author: User
Tags compact modifiers

Concept Virtual machine is an abstract computer, which is realized by simulating various computer functions on the actual computer. Java Virtual machine has its own perfect hardware architecture, such as processor , stack , register , etc., also has the corresponding instruction system. The JVM masks information that is relevant to the operating system platform, allowing Java programs to run without modification on multiple platforms by generating only the target code (bytecode) that runs on the Java Virtual Machine .

Run Process

The bounden duty of a runtime Java Virtual machine instance is to be responsible for running a Java program. When a Java program is started, a virtual machine instance is created. When the program shuts down, the virtual machine instance also dies. If you run three Java programs concurrently on the same computer, you will get three instances of the Java virtual machine. Each Java program runs in its own instance of the Java virtual machine.

The Java Virtual machine instance runs a Java program by invoking the main () method of an initial class. and this main () method must be common (public), static, return value void, and accept an array of strings as arguments. Any class that has such a main () method can be used as a starting point for the Java program to run.



The following is a concrete example of how the process works. The virtual machine is started by invoking the method of a specified class, main, and passed to main a string array parameter, causing the specified class to be loaded, linking other types used by the class, and initializing them. For example, a program:
public class HelloApp {public static void main (string[] args) {System.out.println ("Hello world!"); for (int i = 0; i < args.length; i++) {System.out.println (args);}}}

after compiling, type in command-line mode: Java HelloApp run virtual machineThe Java Virtual machine will be started by calling HelloApp's method main, passing to main an array containing three strings "run", "virtual", "machine". Now we outline the steps that the virtual machine may take when executing the HelloApp. started trying to execute the main method of class HelloApp and found that the class was not loaded, that is, the virtual machine does not currently contain a binary representation of the class, and the virtual machine uses ClassLoader to try to find such a binary representation. If this process fails, an exception is thrown. After the class is loaded and before the main method is called, the class HelloApp must be linked to and initialized with other types. The link consists of three phases: inspection, preparation and resolution. The test examines the symbols and semantics of the loaded main class, prepares to create a static domain of the class or interface, and initializes these fields to the standard default values, and resolves the symbolic references that are responsible for checking the main class to other classes or interfaces, which is optional in this step. The initialization of a class is the execution of a static initialization function declared in a class and the initialization of a static domain. A class must have its parent class initialized before it is initialized.

In the example above, the main () method in the initial class of the Java program will be the starting point of the program's initial thread, and any other threads are started by this initial thread.

There are two types of threads inside a Java Virtual machine: The daemon thread and the non-daemon thread. A daemon thread is typically used by a virtual machine, such as a thread that performs garbage collection tasks. However, a Java program can also mark any thread it creates as a daemon thread. The initial thread in the Java program-the one that started with main ()-is a non-daemon thread.

This Java program continues to run as long as any non-daemon threads are running. When all non-daemon threads in the program are terminated, the virtual machine instance automatically exits. If the security Manager allows, the program itself can be exited by invoking the runtime class or the exit () method of the System class.


Java Virtual Machine architectureis a structure diagram of a Java virtual machine, each Java Virtual machine has a class loading subsystem that mounts the type (class or interface) according to the given fully qualified name. Similarly, each Java virtual machine has an execution engine that is responsible for executing instructions that are contained in the methods of the loaded class.


Execution Engine

After the ClassLoader loads the bytecode into memory, the execution engine reads the Java bytecode as a unit of Java bytecode instructions. The problem is that now the Java bytecode machine is not readable, so you must also find ways to convert the bytecode into platform-related machine code. This process can be performed by an interpreter, or it can be done with an instant compiler (JIT Compiler).

Execution engine is the core of JVM executing Java bytecode, which is mainly divided into explanation execution, compiling execution, adaptive optimization execution and hardware chip execution mode.

The JVM's instruction set is based on stacks rather than registers, and the advantage is that it makes the instructions as compact as possible and facilitates fast transmission over the network (not forgetting that Java was originally designed for the network), and that it was easy to adapt to a platform with fewer general-purpose registers and to facilitate code optimization. Because Java stacks and PC registers are thread-private, threads cannot interfere with each other's stacks. Each thread has a separate instance of the JVM execution engine.

JVM directives consist of a single-byte opcode and several operands. For instructions that require an operand, the operand is usually pressed into the operand stack, even if the local variable is assigned a value, and then the stack is first assigned. Note that this is a "normal" situation, and then you'll talk about exceptions due to optimizations.

1. Interpretation and execution

Similar to some dynamic languages, the JVM can interpret the execution byte code. The Sun JDK uses a token-threading approach, and interested students can take a closer look.

There are several optimization methods for interpreting execution:

A. Stack top cache

The value at the top of the operand stack is cached directly on the register, and for most instructions requiring only one operand, there is no need to re-enter the stack, which can be computed directly on the register, and the result is pressed into the operand station. This reduces the switching overhead of registers and memory.

B. Partial stack frame sharing

The called method can use the operand stack in the call method stack frame as its own local variable area, which reduces the cost of copying parameters when obtaining the method parameters.

C. Executing machine instructions

In some special cases, the JVM executes machine instructions to increase speed.

2. Compile and Execute

To speed up execution, the Sun JDK provides support for compiling bytecode into machine instructions, primarily using the JIT(just-in-time) compiler to compile at run time, which compiles the bytecode to machine code and caches the first time it is executed, and can then be reused. Oracle JRockit uses full compilation execution.

3. Adaptive optimization Execution

The idea of adaptive optimization execution is that the 10%~20% code in the program takes up the execution time of the 80%~90%, so the execution efficiency can be greatly improved by compiling the few pieces of code into the optimized machine code. The typical representative of adaptive optimization is Sun's hotspot VM, which, as its name indicates, the JVM monitors the execution of the code, and when it is determined that a particular method is a bottleneck or hotspot, a background thread is started and the bytecode of the method is compiled into extremely optimized, statically linked C + + code. When the method is no longer a hot zone, the compiled code is canceled and the interpretation is performed again.

Adaptive optimization Not only uses a small amount of compilation time to achieve most of the efficiency gains, but also because of the implementation process of monitoring at all times, the internal code and other optimization has played a big role. Because of the object-oriented polymorphism, a method may correspond to many different implementations, and adaptive optimization can greatly reduce the size of the inline function by monitoring only those code used in the inline.

The Sun JDK is compiled with two modes: client and server mode. The former is more lightweight and consumes less memory. The latter has a higher optimization program and more memory.

In server mode, the escape analysis of the object is performed, that is, whether the object in the method is used outside the method, and if it is used by another method, the object is escaped. For non-escaping objects, the JVM allocates objects directly on the stack (so the object is not necessarily allocated on the heap), the thread gets the object faster, and when the method returns, it facilitates garbage collection of the object because the stack frame is discarded.






When a Java Virtual machine runs a program, it needs memory to store many things, such as bytecode, other information from the loaded class file, objects created by the program, parameters passed to the method, return values, local variables, and so on. Java Virtual machines organize these things into several "runtime data areas" for ease of administration.

Some run-time data areas are shared by all threads in the program, and others are owned by only one thread. Each Java virtual machine instance has a method area and a heap that are shared by all the threads in the virtual machine instance. When a virtual machine loads a class file, it parses the type information from the binary data contained in the class file. These types of information are then placed in the method area. When the program is running, the virtual opportunity puts all objects created by the program at run time into the heap.

run-time data area

Program counter (PC Register): The line number indicator of the byte code executed by the current thread

Java Virtual machine stack : describes the memory model that the Java method executes , and when each method is executed, it creates a stack frame for storing local variable tables, operation stacks, dynamic links, method exits, and so on. When this method is finished, the corresponding stack frame pops up. if the requested stack is too deep, the virtual machine may throw a stackoverflowerror exception if the virtual machine stack is allowed to dynamically expand in the implementation of the virtual machine, when the memory is not sufficient to extend the stack , a outofmemoryerror exception is thrown.

Local method stack : the native method service that is used for the virtual machine.

java heap : a chunk of memory that is shared by all threads and created when the virtual machine is started. All object instances and arrays are allocated on the heap .

method Area : A thread-shared memory area that stores class information loaded by a virtual machine, constants, static variables, and code data compiled by the immediate compiler ( The memory recovery target for this area is primarily for the collection of constant pools and for the unloading of types.

The method area is shared between threads, and when two threads need to load one type at the same time, only one class requests ClassLoader loading and the other thread waits.

For each loaded type, the following information is saved in the method area:

    • The fully qualified name of the class and its parent class (Java.lang.Object has no parent)
    • Type of Class (class or Interface)
    • Access modifiers (public, abstract, final)
    • A list of fully qualified names of the implemented interfaces
    • Constant pool
    • Field information
    • Method information
    • Static variables in addition to constants
    • ClassLoader references
    • Class reference

For each field, the following information is saved in the method area (the field declaration order is also saved):

    • Field name
    • Type of field
    • Modifier for field (public, private, protected, static, final, volatile, transient)

For each method, the following information is saved in the method area (the method declaration order is also saved):

    • Method name
    • Method return type (or void)
    • Parameter information
    • Method modifiers (public, private, protected, static, final, synchronized, native, abstract)

If the method is not an abstract method and is not a local method (Native), the following information is also saved:

    • Byte code of the method
    • The size of the local variable table and the operand stack
    • Exception table

A virtual machine needs to store some data to quickly access a method in a class object, typically implemented as a method table.

Another part of the method area is the run-time-constant pool, which is used primarily to store literal and symbolic references generated during compilation, and constants can be generated at run time, such as the Intern method of string.

GC may also exist in the method area, but the virtual machine specification does not require it, mainly to reclaim some constants and unload some of the unused type information, but the condition of unloading a class is difficult to achieve, and in some cases the GC does not actually reclaim much memory.


data areas shared by all threads

When each new thread is created, it will get its own PC Register (program counter) and a Java stack, and if the thread is executing a Java method (not a local method), then the value of the PC register will always point to the next instruction to be executed. Its Java stack always stores the state of the Java method call in the thread-including its local variables, the arguments that are called simultaneous, the return value, and the intermediate results of the operation. The state of a local method call is stored in a local method stack in a way that relies on a specific implementation, or in a register or some other memory area that is related to a particular implementation.

The Java stack is made up of many stack frames, and a stack frame contains the state of a Java method call. When a thread calls a Java method, the virtual machine presses a new stack frame into the thread's Java stack, and when the method returns, the stack frame is ejected from the Java stack and discarded.

The Java Virtual machine has no registers and its instruction set uses the Java stack to store intermediate data. The reason for this design is to keep the instruction set of the Java Virtual machine as compact as possible, and also to facilitate the implementation of Java virtual machines on platforms that have very few common registers. In addition, this stack-based architecture of Java virtual machines also facilitates the code optimization of dynamic compilers and instant compilers that are implemented by some virtual machines at runtime.

Depicts the memory area created by the Java Virtual machine for each thread, which is private, and no thread can access the PC registers or Java stacks of another thread.


thread-specific run-time data area



Shows a snapshot of a virtual machine instance, which has three threads executing. Thread 1 and thread 2 are executing Java methods, while thread 3 is executing a local method.

The Java stack grows downward, and the top of the stack is displayed at the bottom of the graph. The stack frame of the currently executing method is represented by a light color, and for a thread that is running a Java method, its PC register always points to the next instruction to be executed. For example, thread 1 and thread 2 are all light-colored, because thread 3 is currently executing a local method, so its PC register-the one in dark color, whose value is indeterminate.


Reference article: http://www.cnblogs.com/java-my-life/archive/2012/08/01/2615221.html



Java Virtual Machine Detailed

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.