How the Java Virtual Machine Works is explained in detail

Source: Internet
Author: User

First, class loading device

Let's take a look at the Java program's running process.


From this block diagram very easy to understand how Java programs work. First, you write the Java code and save it to the hard drive. Then you enter it in the command line

Javac Yourclassname.java

At this point, your Java code is compiled into a bytecode (. Class). If you are in the Eclipse IDE or other development tools, you save the Code, the development tools have helped you complete the above compilation, so you can see the class file under the corresponding folder. The class file is still saved on your hard disk, so when you execute it on the command line

Java yourclassname

Finished the work in the red box above. The JRE's loader reads the class file from the hard disk and loads it into the memory area allocated to the JVM by the system-the runtime data areas. Then run the engine to interpret or compile the class file, into a specific CPU machine code, the CPU runs the machine code, the entire process is complete.


Next, focus on what the class loader really is. And how does it work?

First look at some of the features of the loader, a little abstract, but always helpful.


"Hierarchical structure

Class loader is organized into a hierarchical relationship, that is, a parent-child relationship. Among them, Bootstrap is the father of all class-loader. For example, as seen in:


--bootstrap class Loader:

When executing a Java virtual machine, this class loader is created, which loads some of the main Java APIs, including the object class. It is important to note that this class loader is not written in the Java language, but is written in C + +.

--extension class Loader:

This loader loads some extension classes outside of the base API, including some classes related to security performance. (Not very deep at the moment, just to say it in general, and then specify it later)

--system Class Loader:

It loads the classes in the application, that is, the classes configured in your classpath.

--user-defined Class Loader:

This is a developer's own definition loader by extending the definition of the ClassLoader class, loaded into some classes of the program ape definition.


"Delegation Mode"

Looking closely at the hierarchy above, when the JVM loads a class, the lower loader will entrust the task to the previous class loader, and the previous layer loads into the namespace that checks it to see if the class is already loaded, assuming that it is already loaded and used directly. Assuming it is not loaded, proceed to the top of the consignment. After inspection, load in reverse order, assuming that the bootstrap loader cannot find the class, then commit to it until the class file is found. For a particular class loader, a Java class can only be loaded once, meaning that in a Java virtual machine, the full identity of the class is (Classloader,package,classname). A ray can be loaded into a different class loader.


Give a detailed example to illustrate, now Tim? I have a custom class MyClass that needs to be loaded, and if not specified, the General Delivery app (System) is loaded. After receiving the task, the system checks whether it has this class in its own library, finds that it has not been entrusted to extension,extension for the same inspection, and found that the topmost boots found no one in his library, and thus relied on its path (Java Core class libraries, such as Java.lang, try to load, did not find this maclass class, so just good (others are optimistic about you, to you over, you can do nothing, just give others) down to pay extension,extension to their own path (java_home/ Jre/lib/ext) is to find, or not find, continue down, at this time the system loader to the Classpath path to find, found, and then loaded into the Java virtual machine.

Now if we put this class in the path of java_home/jre/lib/ext (equivalent to the extension loader), according to the same rules, and finally loaded by the extension loader into the MyClass class, see, Unified types are loaded into the JVM two times, but each time it is completed by a different classloader.


"The visibility limits of

The lower loader can see the class in the upper loader, and vice versa, that is to say that the trust can only go from bottom to top.


"Does not agree to uninstall class

A class loader can load a class, but it cannot unload a class. However, the class loader can be deleted or created.


When the class is loaded, the JVM continues to follow the rest of the work:


The steps in the block diagram are as follows:

Loading: The class loaded in the article, loading the class file in the filesystem into the JVM memory (execution data region)

Verifying: Checks whether the loaded class file conforms to the Java specification and the virtual machine specification.

Preparing: Allocates the required memory for this class, determines the data structure required for the class's properties, methods, and so on. (Prepare a data structure that assigns the memory required by classes and indicates the fields, methods, and Interfaces de Fined in the class.)

Resolving: Changes the symbol reference in the constant pool to a direct reference. (Not very understanding)

Initialing: Initializes a local variable of the class, assigns a value to the static domain, and runs the static initialization block at the same time.


So, what exactly did class loader do when it loaded the class?

To understand the details of this, you must first specify the execution data area.


II. implementation of data areas

Runtime Data areas: When executing a JVM Demo sample, the system assigns it a chunk of memory (the size of the memory area can be set), which is managed by the JVM itself. A chunk from this piece of memory is used to store some execution data, such as objects created, arguments passed to methods, local variables, return values, and so on. This piece of information is called the execution data area. The execution data region can be divided into 6 chunks: Java stack, program count Register (PC register), local method Stack (Native methods stack), Java heap, method area, execution Chang (Runtime Constant Pool). The execution of a constant pool should belong to the method area, but because of its importance, the JVM specification independently describes it. , the previous 3 regions (PC Registers, Java stacks, local method stacks) are owned by each thread on its own, and the latter three are owned by all the threads in the entire JVM instance. These six chunks are for example with what is seen:


"PC Counter:

Each thread has a PC counter, and when the thread starts (start), the PC counter is created, which holds the address of the bytecode instruction (JVM directive) that is currently being run.

"Java stack:

Identically, the Java stack is also owned separately by each thread, which is created when the thread starts. This stack holds a series of stack frames, and the JVM can only perform both push and eject (POP) stack frames. Whenever a method is called, the JVM presses a stack frame into the stack, and the stack frame pops up when the method finishes returning. Assuming that the method runs with an exception, you can call Printstacktrace and other methods to view the stack. For example the following stack:


Ok. Now let's look specifically at what's in each stack frame. From very easy to see, each stack frame consists of three parts: a local variable array, an operand stack, and a Chang reference to the class to which the method belongs.

Local (local) array of variables:

In an array of local (local) variables , starting from 0, the reference to the object to which the method belongs, the parameters passed to the method, and the local variables are stored sequentially. To give a sample example:

public void dosomething (int A, double b, Object o) {...}

The contents of the local variables stored in the stack frame of this method are each:

0:this1:a2,3:b4:0

Look carefully, in which a double type B requires two consecutive indexes. When the value is taken, the value in this index is taken out of 2. Assuming it is a static method, the array No. 0 does not hold the this reference, but instead stores the passed parameters directly.

"Operand stack:

some intermediate variables in the operand stack where the method is run, and the JVM presses or pops the variables as it runs the method. In fact, the operand stack is where the method really works, and when you run the method, the local variable array and the operand stack are exchanged for data based on the method definition. For example, when you run the following code, the operations of the stack are as follows:

int a = 90;int b = 10;int C = a + B;


Note In this diagram, the point of the operand stack is on top, so the first 100 bits are pushed above. It can be seen that the operand stack is actually a temporary storage area of data, storing some intermediate variables, the method is over, and the operand stack is gone.

"Stack frame Data reference:

In addition to the local variable array and the operand stack, the stack frame requires a reference to a constant pool. When the JVM runs to data that requires a constant pool, this reference is used to access the constant pool. The data in the stack frame is also responsible for handling the return and exception of the method. Assuming that return is returned by return, the stack frame of the method is ejected from the Java stack. Assuming that the method has a return value, the return value is pressed into the operand stack of the method that called the method. In addition, a reference to the possible exception table for the method is also saved in the data area. The following examples illustrate:

Class example3c{public    static void Addandprint () {        double result = Addtwotypes (1,88.88);        SYSTEM.OUT.PRINTLN (result);    }    public static double addtwotypes (int i, double d) {    return i+d;    }}

When you run the above code, the Java stack, for example, looks like this:


Take some time to study it well. It is important to note that the bottom of the stack is above, the stack frame of the Addandprint method is first placed, and then pressed into the stack frame of the Addtwotypes method. The rightmost text indicates that there is an error and should be that the addtwotypes run result is stored in the Addandprint's operand stack.

"Local Method Stack

When a program calls local methods (such as C or C + + code) through JNI (Java Native Interface), the corresponding stack is established based on the language type of the local method.

"Method Area

The method area is shared by all threads in a JVM instance, and the method area is created when a JVM instance is started. It is used to deposit the execution of a constant pool, information about fields and methods, and bytecode for static variables, classes, and methods. Different implementations of the JVM differ in how the method area is implemented. The hotspot of Oracle is called the Permanent Zone (Permanent area) or the permanent generation (Permanent Generation).

"Executes a constant pool

This area holds constants for classes and interfaces, and in addition, it holds all references to methods and fields. When a method or domain is referenced, the JVM finds the actual address of the method and domain in memory by executing these references in the constant pool.

(heap)

The heap contains objects or instances that are created by the program. This area has a very large impact on the performance of the JVM. The garbage collection mechanism deals with this area of memory.

Therefore, the class loader loading is actually based on the compiled class file, the Java bytecode loaded into the JVM memory, and finished the operation of the data in the initialization work for the running engine to run.


Third, running engine (execution engines)

After the class loader loads the bytecode into memory, the runtime engine reads the Java bytecode with the Java bytecode directive as a wish. The problem is that today's Java bytecode machines are unreadable, so you must also try to convert bytecode into platform-related machine code. This process can be run by an interpreter, or it can have an instant compiler (JIT Compiler) to complete.





How the Java Virtual Machine Works is explained in detail

Related Article

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.