Introduction to the JVM (ii)

Source: Internet
Author: User

1 JVM Introduction

The JVM is the most basic foundation of our Javaer, when we first started to learn Java, we usually start with "Hello World", then write a complex point class, then find some open source frameworks, such as spring,hibernate and so on, Then the development of enterprise-class applications, such as Web sites, enterprise applications, real-time trading system, and so on, until one day suddenly found that the system is so slow, and from time to time a memory overflow something, today is the trading system reported Stackoverflowerror, Tomorrow is the site system reported a outofmemoryerror, this error is difficult to reproduce, only the analysis of Javacore and dump files, good luck can also analyze a result, run the point, go directly to the temple incense! Every day to pick up the customer's phone is trembling, for fear of what a moth. I think Java has this experience for a long time, so where is the ultimate root knot of these problems? --JVM.

The JVM's full name is the Java Virtual Machine,java VM, which is a virtual machine on a computer, which is not the same as we use VMware, the virtual thing you can see, the JVM you can't see, it's in memory. We know that the basic composition of the computer is: the operator, controller, memory, input and output devices, the JVM also has this set of elements, the operator is of course, the hardware CPU is also processed, just in order to adapt to "once compiled, run anywhere" situation, need to do a translation action, So I used the JVM's own command set, which is a bit like the assembly command set, each assembly command set for a series of CPUs, such as the 8086 series of the assembly can also be used in 8088, but cannot run on 8051, and the JVM command set can be run everywhere, Because the JVM does the translation, it translates into different machine languages depending on the CPU.

The most profound thing we need to understand in the JVM is its storage part, storage. Hard disk? No,no, the JVM is an in-memory virtual machine, its storage is memory, we write all the classes, constants, variables, methods are in memory, which determines whether our program is robust, efficient, and the next part is the focus of the introduction.

2 Components of the JVM

Let's first draw the JVM into this virtual machine, as shown in:

As you can see from this diagram, theJVM is running on top of the operating system, and it has no direct interaction with the hardware. Let's look at the components of the JVM, as shown in:

This diagram is a reference to the network's widely circulated JVM composition diagram, which is divided into four parts for the entire JVM:

Class Loader ClassLoader

The role of the ClassLoader is to load the class file into memory, such as writing a Helloword.java program and then compiling it into a class file through Javac, how can it be loaded into memory to be executed? Class loader is responsible for this, it is not possible to create a. class file can be loaded, class loader loaded class file is a format requirement, in the "JVM specification" Chinese-style definition class file structure:

Classfile {

U4 Magic;

U2 minor_version;

U2 major_version;

U2 Constant_pool_count;

Cp_info Constant_pool[constant_pool_count-1];

U2 access_flags;

U2 This_class;

U2 Super_class;

U2 Interfaces_count;

U2 Interfaces[interfaces_count];

U2 Fields_count;

Field_info Fields[fields_count];

U2 Methods_count;

Method_info Methods[methods_count];

U2 Attributes_count;

Attribute_info Attributes[attributes_count];

}

If you need to know more, you can read the fourth chapter "the Class File Format" in "JVM Specification", which is no longer explained in detail.

Friendly tip: Class loader just load, as long as the file structure to load, as to say can not run, it is not responsible for it, that is the responsibility of execution engine.

Execution engine Execution engines

The execution engine, also called the Interpreter (interpreter), is responsible for interpreting the command and committing the operating system execution.

Native Interface Local Interface

The role of the local interface is to integrate different programming languages for Java, it is the original intention is to merge C/s program, Java was born when the C + + time is rampant, in order to foothold, must have a smart, wise call C + + program, So, in memory, there is an area dedicated to processing code labeled native, it is the practice of native method stack registered native methods, the execution engine when the execution of native libraies load. At present, this method is used more and more, unless it is a hardware-related application, such as a Java program to drive a printer, or Java systems to manage production equipment, in enterprise applications has been relatively rare, because the current heterogeneous domain communication is very developed, such as the use of socket communication, You can also use Web service and so on, do not introduce more.

Runtime data area run Datastore

Running the data area is the focus of the entire JVM. All of our written programs are loaded here before they start running, and the Java ecosystem is thriving, thanks to the region's excellent autonomy, which is detailed in the next section.

The entire JVM framework is loaded by the loader file, and then the actuator processes the data in memory, and the need to interact with heterogeneous systems can be done through a local interface, see, a complete system was born!

2 JVM Memory Management

All data and programs are stored in the running data area, which includes the following sections:

Stack stack

Stack is also called the stack memory, is the Java program's runtime, is created when the thread is created, its life is followed by the life of threads, thread end stack memory is released, there is no garbage collection problem for the stack, as long as the end of the thread, the stack over. The question is: What data is stored in the stack? And what is the format?

The data in the stack is in the format of stack frame, the stack frame is a memory block, is a data set, is a data set about method and run-time data, when a method A is called, it generates a stack frame F1, and is pressed into the stack, a method calls the B method , the resulting stack frame F2 is also pressed into the stack, after execution, the first pop-up F2 stack frame, and then pop F1 stack frame, follow the "advanced after out" principle.

What data is there in the stack frame? The main storage of the stack frame is 3 kinds of data: local variables (locally Variables), including input parameters and output parameters as well as variables within the method, stack operation (Operand stack), record stack, stack operation, stack frame data, including class files, methods and so on. The light is more boring, we draw a diagram to understand the Java stack, as shown in:

Shown in a stack of two stack frames, stack frame 2 is the first method to be called, first into the stack, then method 2 calls the Method 1, the stack frame 1 is at the top of the stack, the stack frame 2 is at the bottom of the stack, after execution, pop up the stack frame 1 and stack frame 2, thread end, stack release.

Heap Heap Memory

There is only one heap class stored in a JVM instance, and the size of the heap memory can be adjusted. After the class loader reads the class file, it needs to put the class, method, and constant variables into the heap memory to facilitate execution by the executor, and heap memory is divided into three parts:

Permanent Space Persistent Storage Area

The persistent storage area is a resident memory area that holds the class,interface metadata that is carried by the JDK itself, that is, it stores the required class information for the running environment, the data that is loaded into this area is not reclaimed by the garbage collector, and the memory that is occupied by this zone is freed by shutting down the JVM.

Young Generation Space New District

The newborn area is the birth, growth, and extinction area of a class, where a class is generated, applied, and finally collected by the garbage collector, ending life. The new district is divided into two parts: Eden Space and the Survivor area (Survivor Pace), all of which are new in the Eden District. There are two surviving areas: Zone 0 (Survivor 0 space) and 1 (Survivor 1 space). When the space in Eden is exhausted, the program needs to create objects, and the JVM's garbage collector will garbage reclaim the Garden of Eden and destroy objects in the Eden area that are no longer referenced by other objects. The remaining objects in the Garden of Eden are then moved to the surviving zone 0. If the surviving zone 0 is full, then the area will be garbage collected and then moved to Zone 1. What if the 1 districts are full? Then move to the retirement area.

Tenure Generation Space Old Breeding

The pension area is used to save Java objects that are screened out from the newborn area, and the general pool objects are active in this area. The three districts are as follows:

Method area

The method area is shared by all threads, and the zone holds all the fields and method bytecode, as well as some special methods such as constructors, where the interface code is defined.

PC Register Program Counter

Each thread has a program counter, which is a pointer to the method byte code in the method area, which reads the next instruction by the execution engine.

Native method Stack Local methods stack

3 JVM-related issues

Q: What is the difference between heaps and stacks

A: The heap is a storage object, but the temporary variables within the object are present in the stack memory, such as the Methodvar in the example is stored in the stack at run time.

The stack is followed by threads, there is a stack on the thread, the heap follows the JVM, and there is a heap of memory on the JVM.

Q: What exactly exists in the heap memory?

Answer: objects, including object variables and Object methods.

Q: What is the difference between a class variable and an instance variable?

A: A static variable is a class variable, a non-static variable is an instance variable, and it is straightforward to say that a variable with a static modifier is an instance variable that has no static modifier. Static variables exist in the method area, and instance variables exist in heap memory.

Q: I heard that class variables are in the JVM start at the beginning of the good, and you say this is different!

Answer: Then you are hearsay, believe me, yes.

Q: Java is the method (function) The value of the pass or the address?

A: No, it is a pass-through address, specifically the value passed by the native data type, the address that the reference type passes. For raw data types, the JVM is handled by copying from the method area or heap to the stack, then running the methods in the frame, and then copying the variables back.

Q: Why does it produce outofmemory produced?

A: There is not enough free memory in the heap memory. This sentence to understand, not to say that the heap has no memory, is that the new application memory object is larger than the heap of free memory, such as the heap is now idle 1M,       But the new application of memory needs 1.1M, so it will be reported outofmemory, may be the object of the application of memory as long as 0.9M, so it only appears once OUTOFMEMORY,GC is also normal, looks like a contingency, that is the case. However, if the GC does not recycle at this time, it will produce a suspend condition, the system does not respond.

Q: I don't have many objects, why do I still have outofmemory? ?

A: You inherit a lot of layers, the heap produces the object is the first generation of the parent class, and then the child class, understand?

Q: OutOfMemory What are the different errors?

A: There are two kinds, namely "Outofmemoryerror:java Heap Size" and "Outofmemoryerror:permgen space", both of which are memory overflow, heap size is that the application is not new memory, this is very common, Check the size of the application or sizing heap memory.

"PermGen space" is because the permanent storage area is full, this is also very common, generally in the hot release environment, because each release of the application system does not restart, over time the permanent storage area of the dead object too many causes the new object can not request memory, general restart can be.

Q: Why does it produce stackoverflowerror ?

A: Because a thread consumes all of the stack memory, it is usually caused by a recursive function.

Q: Multiple JVMs can be viewed on a single machine it? can I exchange visits between the JVMs?

A: You can have multiple JVMs, as long as the machine withstands it. There is no exchange of visits between the JVMs, and you cannot access the B-JVM heap memory in A-JVM, which is not possible. In previous versions of the JVM, the presence of A-JVM crack affected B-JVM, and now the version is very rare.

Q: Why does the Java use a garbage collection mechanism instead of C/ explicit memory management?

A: In order to be simple, memory management is not every programmer can toss good.

Q: Why didn't you describe the garbage collection mechanism in detail?

A: Garbage collection mechanism of each JVM is different, the JVM specification just define to automatically free memory, that is, it only defines the garbage collection abstract method, how to implement the various vendors are different, the algorithm varies, this thing really does not need to go deep.

Q: JVM in the end, which areas are shared? What is private?

A: The heap and method area are shared, others are private,

Q: What is JIT , why didn't you say?

A: JIT refers to just in time, some documents to the JIT as a part of the JVM to introduce, and some as part of the implementation of the engine to introduce, which is understandable. Java was born in an explanatory language, don't shush, even if compiled into a bytecode (byte code) is also for the JVM, it needs to be translated into the native code (native) to be executed by the machine, so the efficiency of the concerns raised. Sun in order to solve the problem put forward a new set of mechanisms, good, you want to compile into native code, no problem, I provide a tool on the JVM, the bytecode compiled into the native code, the next time you come to visit the native code directly to become, so the JIT was born, and so on.

Q: JVM What other parts did you not mention?

A: The JVM is an unusually complex thing, writing a brick book is not too much, there are a few to explain:

Chang (Constant Pool): the area in which the constants in the program are stored sequentially and indexed. For example, int i = 100, this 100 is placed in the constant pool.

Security Manager: Provides security controls for Java runtime to prevent malicious attacks, such as specifying read files, write file permissions, network access, create processes, and so on, Class loader in security The manager authentication is passed before the class file can be loaded.

Method Index Table (Methods table), which records the address information for each method, and the address pointers in the stack and heap actually point to the Methods table address.

Q: Why not suggest an explicit life System.GC in the program () ?

A: Because the explicit declaration is to do a full scan of heap memory, that is, the complete GC, it is necessary to stop all activities (Stop the World Collection), your application can withstand this?

Q: JVM What are the adjustment parameters?

A: Very much, to find their own, heap memory, stack memory size can be defined, even the heap memory of three parts, the new generation of the various scales can be adjusted.

Original connection:

Http://www.360doc.com/content/10/1125/19/4154133_72389630.shtml

Introduction to the JVM (ii)

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.