JVM basics and tuning (2)

Source: Internet
Author: User

Memory architecture of Java Virtual Machine

After learning about the JVM basics, let's take a look at the memory architecture of the Java Virtual Machine. This is a prerequisite for understanding the JVM garbage collection algorithm, after understanding the memory structure, we can optimize different parts according to our program. The Java heap and stack have been described above, but the Java memory system is not described here.

This section,Mainly to learn the basic structure of JVM, That is, the overview. I have a lot of content and a large number of concepts. But you don't have to worry about the concept. I have full confidence to turn the concept into a graph in your mind, so as long as you are patient, careful, serious, and make full use of your imagination, you will be confident in this chapter. Of course, I don't mean to understand JVM after reading this chapter,JVM has a lot of knowledge to learn.. After reading this section,We will learn more about JVM in the future.But if youComplete this sectionTo learn,Learning Other JVM details will get twice the result with half the effort.

Knowledge Point 1: What is a Java Virtual Machine?

Step 1:First, write a class:

    package test;  public class JVMTestForJava {  public static void main(String[] args) throws InterruptedException {          Thread.sleep(10000000);  }  }

Step 2:CMD Window input: Java test. jvmtestforjava

Step 3:Open Task Manager-Process

You can see that the program named java.exe does not exist. This is the Java Virtual Machine. the Java XXX command is used to start a Java virtual machine, and the main function is the entry of a Java application. When the main function is executed, the Java Virtual Machine is started.Okay, CTRL + C, and end your JVM.

Step 4:Open your ecplise, right-click Run application, and run application again

Step 5:Open Task Manager-Process

Well, I have already noticed that there are two javaw.exe. Why are there two? Because we ran the run application twice just now.In this case, I want to notify you that a Java applicationcorresponds to a java.exe/javaw.exe(java.exeand javaw.exe. You can regard it as a Java virtual machine, one with a window interface and one without a window interface ). You can run several applications on java.exe/javaw.exe. Or, more specifically, you run several main functions to start several Java applications and several Java virtual machines.

------ Main method, program entry

Knowledge Point 1 Summary:To start a virtual machine instance.

Knowledge Point 2: JVM Lifecycle

Basically, when learning a container (more specifically when learning servlet), we need to learn its lifecycle. What is the JVM lifecycle?

Step 1: Test the Code:

Package test; public class jvmtestlife {public static void main (string [] ARGs) {New thread (New runnable () {@ overridepublic void run () {for (INT I = 0; I <5; I ++) {try {thread. currentthread (). sleep (I * 10000); system. out. println ("sleeping" + I * 10 + "seconds");} catch (interruptedexception e) {system. out. println ("Why wake me up ");}}}}). start (); For (INT I = 0; I <50; I ++) {system. out. print (I );}}}

Step 2:Run application in ecplise

Step 3:Open the task manager.

Step 4:The butler console outputs and observes when javaw.exe in the Task Manager disappears.

[Java]View plaincopy

  1. 0: Sleeping 0 seconds
  2. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 28 29 30 31 32 33 34 35 36 38 39 40 41 42 43 44 45 46 48 49 sleep for 10 seconds
  3. Sleeping for 20 seconds
  4. Sleeping for 30 seconds
  5. Sleep for 40 seconds

This is the output result in ecplise. if you observe the console and the task manager's javaw.exe, you will find that when the for loop of the main function is printed, the program does not exit, and javaw.exe will exit after the runner-up of the entire New thread(example is executed. We know that in C ++'s Win32 programming (creatthread (), the main function is finished and the boarding thread is exited. in C #, if you use threadpool) the conclusion is that all threads end with the end of the host process. But in Java, it seems that there is a lot of difference with our cognition. Why?

This is becauseJava virtual machines have two types of threads: a daemon thread and a non-daemon thread.The main function is a non-daemon thread, and the GC of the virtual machine is a daemon thread. In a Java virtual machine, as long as any non-daemon thread has not ended, the instance of the Java Virtual Machine will not exit, so even if the main function is not the daemon thread, however, since the anonymous thread started in the main function is also a non-daemon thread, it is not over yet, so the JVM cannot exit (do you want to do something bad ??).

Knowledge Point 2 Summary:The life cycle of a Java VM. When the main function of a Java application is started, the VM is also started. the life cycle of a Java VM instance ends only when all non-Daemon Processes in the VM instance end.

------ The method runtime addshutdownhot provided by JDK can be executed when the Virtual Machine exits.

Knowledge Point 3: Architecture of Java Virtual Machine

Before learning about the JVM structure, we need to first understand the basic memory structure of the operating system.

Operating system memory layout:

How does the JVM express it in the operating system?

JVM in the operating system

Why is the JVM memory distributed in the heap of the operating system ?? Because the stack of the operating system is managed by the operating system, it will be recycled at any time. Therefore, if the JVM is placed in the stack, it is difficult to determine who will recycle a null Java object, the existence of GC makes no sense at all, and it is also necessary to consider the JVM to automatically release the stack. Therefore, it is best to put it in the heap.

Simple memory layout of operating system + JVM

In this case, have you found that the JVM memory structure is surprisingly consistent with the operating system structure? Can you seat them? No, it doesn't matter. Let's take a look at the figure again. I will help you to seat your account.See the red note below.

From this figure, you can easily find that the original JVM design model is actually an operating system model,Operating system-basedAngle,JVMFind the dead java.exe/javaw.exe,That is, an application, AndClass-basedFor files, JVM is an operating system, and the JVM method area is equivalent to the hard disk area of the operating system. So, do you know why I like to call the permanent area, because this word is permanent, that is, permanent zone, and our disk is a permanent zone with continuous power, it means the same thing. How can this problem be solved. The java stack and the operating system Stack are consistent, regardless of the growth direction or management method. As for the stack, although the conceptual consistency goal is also consistent, the memory allocation method is always (new, or malloc, etc.), but due to their different management methods, JVM is GC collection, while the operating system is manually released by programmers, therefore, there are many differences in algorithms. The GC collection algorithm is probably a classic in JVM. We will learn it a little later. Don't worry.

See the following figure.

What is the difference between this image and the above image? Yes, I have a PC register. Why do I need to draw it out? I want to tell you the so-called PC register, whether in a virtual machine or in the operating system hosted by our virtual machine, the functions are consistent,The PC register on the computer is the hardware on the computer.It is originally a computer. (This is easy for those who have learned assembly. There are many 32-bit registers such as eax and ESP, registers in JVM are equivalent to ESP registers in assembly ),The computer uses a PC register to store "pseudo commands" or addresses., AndCompared with virtual machines,The PC register is represented as a piece of memory (One Word Long, the virtual machine requires the word length to be at least 32 characters),Virtual Machine PC registerThis function also stores pseudo commands. More specifically, it stores the address of the command to be executed, and it can even be the local address of the operating system command, when the method being executed by the virtual machine is a local method, the value of the jvm pc register storage is undefined, so you should know clearly now,The PC register of the VM is the address (byte code stream) used to store the next command to be executed).

What's more? A classloader is added. In fact, this figure is to tell you that when a classloder is started, the location of the classloader is located in the heap of JVM, and then it will attach a to the host's hard disk. class is loaded into the JVM method area, the byte file in the Method Area will be taken by the Virtual Machine new A bytecode (), and then a bytecode object is generated in the heap memory, and thenThe a-byte code memory file has two reference class objects pointing to a and one pointing to loading its own classloader., Such.

So what information does the bytecode memory block in the Method Area record in addition to a Class Object reference and a classloader reference that loads itself ?? Let's take a look at the picture, and then I will tell you what we will never forget.

Do you carefully map this bytecode to our class? Is it surprisingly consistent with a basic Java class? The following shows the basic structure of a Class I posted.

[Java]View plaincopy

  1. Package test; import java. Io. serializable; public final class classstruct extends object implements serializable {// 1. class information
  2. // 2. Object Field Information
  3. Private string name;
  4. Private int ID;
  5. // 4. Constant pool
  6. Public final int const_int = 0;
  7. Public final string const_str = "const_str ";
  8. // 5. Variable-like area
  9. Public static string static_str = "static_str ";
  10. // 3. Method Information
  11. Public static final string getstatic_str () throws exception {
  12. Return classstruct. static_str;
  13. }}

Have you found out that the above code annotation corresponds to the above bytecode memory block by label, in fact, the bytecode block of the memory is the complete package of your entire class into the memory.

SoThe information recorded in each information segment can be obtained from our class structure. You do not need to memorize it. If you have carefully read the descriptions below, it is impossible to forget it.:

1. class information:Modifier (public final)

Is it a class or an interface)

Class Name (test/classstruct. Class)

Full qualified name of the direct parent class (Java/lang/object. Class)

The permission name array of the direct parent interface (Java/IO/serializable)

That is, information extraction from the description of public final class classstruct extends object implements serializable

2. Field Information:Modifier (pirvate)

Field Type (Java/lang/string. Class)

Field name (name)

This is similar to private string name; extraction of the description

3. method information:Modifier (public static final)

Method return value (Java/lang/string. Class)

Method Name (getstatic_str)

The size of the local variable required by the parameter and the size of the operand stack (we will talk about the operand stack later)

The byte code of the method body (that is, the content in curly brackets)

Exception table (throws exception)

That is, to extract the bytecode of the public static final string getstatic_str () throws exception method.
4. Constant pool:

4. 1. Direct constants:

1.1constant _ ingeter_info integer directly constant pool public final int const_int = 0;

1.2constant _ string_info string direct constant pool public final string const_str = "const_str ";

1.3constant _ double_info floating point type direct constant pool

And so on. (A class will be decompiled later to view its constant pool .)

. Method Name, method descriptor, class name, field name, and symbol reference of field descriptor

That is, the compiler can be identified and the content that can be quickly searched is stored here. It accesses the content through indexes like an array and is specially used for searching.

During compilation, we can determine that all constants of a value will be copied to its own constant pool or embedded into its byte code stream. As a constant pool or a part of the byte code stream, the compilation frequency is stored in the method area, just like a common class variable. However, when common class variables are stored as part of their types, the compilation frequency is saved as part of their types.

5. class variables:

Is a static field (public static string static_str = "static_str ";)

Before using a class, virtual machines must allocate space for these class variables in the method area.

6. A reference to classloaderThrough this. getclass (). getclassloader (), why should we first pass through the class? Think about it, read the explanation at the seventh point, and come back to think about it.

7. A reference to a Class ObjectThis object stores information about all the bytecode memory blocks. So you can see the area, such as: class information, you can get through this. getclass (). getname ()

You can use this. getclass (). getdeclaredmethods (). You can use this. getclass (). getdeclaredfields (), and so on, so what you want in the bytecode, called, can be basically done for you through the class reference. Because it is an object of bytecode in the memory block in the heap

8. method table,If you learn C ++, you should know that the Object Memory Model of C ++ has something called a virtual table. Java is originally named C ++ --, its method table is actually a virtual table of C ++, and its content is the direct reference of all instance methods that the class may be called. It is also a cache-like search table for Fast Location of dynamic binding, which exists in the memory in the form of arrays. However, this table does not have to exist. It depends on the Virtual Machine designer and whether the machine running the virtual machine has enough memory.

First, before a program is started, its class will beClass LoaderLoadMethod Area(Not nice. In fact, this area is called the permanent area ),Execution engineRead the bytecode in the method area for adaptive parsing, and parse and run (one of them), and thenPC registerPoint to the location where the main function is located. The VM startsJava stackReserve a stack frame (each method corresponds to a stack frame), and then start to run the main function. The code in the main function is mapped to the corresponding implementation in the operating system by the execution engine, then callLocal method InterfaceWhen the local method is running, the control system will allocate the local methodLocal method StackTo store some temporary variables, run local methods, call the operating system APII, and so on.

Reprinted article: http://blog.csdn.net/yfqnihao has changed.

JVM basics and tuning (2)

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.