Java Advanced Chapter (second, JVM memory model, memory management)

Source: Internet
Author: User
Tags garbage collection numeric value throw exception wrapper

This article is transferred from https://zhuanlan.zhihu.com/p/25713880. Basic concepts of the JVM

The Chinese name of the JVM is called a Java Virtual machine, which is a virtual computer run by software technology that simulates a computer.

The JVM also acts as a translator, and the Java program we write is not directly identifiable by the operating system, and the JVM is responsible for translating our program to "listen" to the system and tell it what we need to do with the program.

We all know that Java programs need to be compiled and generated. class file, the JVM can recognize and run it, the JVM develops its interpreter for each operating system, so as long as its operating system has a corresponding version of the JVM, then this Java compiled code will be able to run, which is why Java can compile and run everywhere.



The life cycle of the JVM

The JVM runs when the Java program starts executing, and it stops when the program ends.

A Java program will open a JVM process, and if you run three programs on a single machine, there will be three running JVM processes.

There are two types of threads in the JVM: Daemon threads and Normal threads

A daemon thread is a thread that the JVM uses itself, such as garbage collection (GC), which is a daemon thread.

Normal threads are usually threads of Java programs, and the JVM will not stop as long as there are normal threads executing in the JVM.

If the permission is sufficient, you can call the exit () method to terminate the program.



The structure system of the JVM



The startup process of the JVM

1. JVM Loading environment and configuration

Before we learn this, one thing we need to know is the difference between JDK and JRE.

The JDK is a developer-oriented SDK that provides a Java development environment and a running environment, with the JRE included in the JDK.

The JRE is the Java operating environment and is intended for all Java program users, including developers.

JRE = Run environment = JVM.

If you have a JDK installed, you will find two sets of JRE in your computer, one set under/java/jre.../and the other in/java/jdk.../jre. So the question is, who decides to run the set of two or more JRE on a single machine? This task falls on Java.exe, and Java.exe's task is to find the right JRE to run the Java program.

Java.exe Select the JRE in the following order:

1. Do you have a JRE under your own directory?

2. There is no JRE in the parent directory

3. Query registry: Hkey_local_machine\software\javasoft\java Runtime environment\ "Current JRE version number" \javahome

The main core of these steps is to find the absolute path to the JVM.

The path to the jvm.cfg is: JRE path \lib\ "CPU Architecture" \jvm.fig

The contents of jvm.cfg are as follows:


-client known
-server known
-hotspot aliased_to-client
-classic WARN
-native ERROR
-green ERROR

Known indicates presence, IGNORE means not present, aliased_to represents an alias to another JVM
WARN indicates that a substitution is not present, an ERROR indicates that no throw exception exists

2. Loading the JVM

Once the path to the JVM is found through the first step, Java.exe is loaded into the JVM file via LOADJAVAVM.
LoadLibrary loads the JVM Dynamic Connection library, and then hooks the ubiquitous functions JNI_CREATEJAVAVM and Jni_getdefaultjavavmintargs in the JVM to Invocationfunction Variables on the CREATEJAVAVM and Getdafaultjavavminitargs function pointer variables. The loading of the JVM is complete.

3. Initialize the JVM and get the local calling interface

Call Invocationfunction-CREATEJAVAVM, the JNI_CREATEJAVAVM method in the JVM, to get an instance of the JNIENV structure.

4. Running Java programs

The JVM runs Java programs in two ways: Jar package and Class
When running the jar, Java.exe calls the Getmainclassname function, which first obtains the JNIEnv instance and then calls Getmanifest () in the Jarfilejnienv class. Take the value of Getattrebutes ("Main-class") from the MANIFEST object it returns, which is the file in the jar package: Meta-inf/manifest. The main class of the Main-class specified by MF is the main class of the run. The main function is then called JAVA.C in the LoadClass method to load the master class (Findclass using the jnienv instance).

When you run class, the main function directly calls the LoadClass method in JAVA.C to load the class.



class file

The class file is generated by the Java compiler, which we created. After the Java file is passed through the compiler, it becomes. class file so that it can be recognized and run by the JVM.



Class loading Subsystem

A class loading subsystem can also be called a classloader, and the JVM defaults to three classloader:

1, BootStrap ClassLoader: called the Startup class loader, is the topmost class loader, responsible for loading the JDK core class library, such as Rt.jar, Resources.jar, Charsets.jar and so on.

2, Extension ClassLoader: called the Extension class loader, is responsible for loading the JAVA extension class library, the default load $java_home in Jre/lib/*.jar or-djava.ext.dirs the jar package under the specified directory.

3, App ClassLoader: called the system ClassLoader, is responsible for loading all the jar and class files in the application Classpath directory.

In addition to the three ClassLoader (loaders) provided by the Java default, we can customize the ClassLoader according to our own needs, and the custom ClassLoader must inherit the Java.lang.ClassLoader class. Two default loaders other than Bootstrap ClassLoader are inherited from Java.lang.ClassLoader. BootStrap ClassLoader is not an ordinary Java class, it is written in C + +, embedded in the JVM kernel, when the JVM is started, BootStrap ClassLoader also started, responsible for loading the core class library, and constructs the extension ClassLoader and the app ClassLoader class loader.

The ClassLoader subsystem is not just responsible for locating and loading class files, it also does a lot of things in strict accordance with the following steps:

1、加载:寻找并导入Class文件的二进制信息2、连接:进行验证、准备和解析     1)验证:确保导入类型的正确性     2)准备:为类型分配内存并初始化为默认值     3)解析:将字符引用解析为直接引用3、初始化:调用Java代码,初始化类变量为指定初始值

For more information, please refer to another article: Java class loading mechanism----Knowledge column



Method area

In the JVM, type information and class static variables are stored in the method area, and the type information is the information that the ClassLoader extracts from the class file during class loading.

It is important to note that the constant pool is also stored in the method area.

All threads in the program share a method area, so the information that accesses the method area must ensure that the thread is secure. If there are two threads to load a class at the same time, then only one thread is allowed to load the class, and the other must wait.

The size of the method area can be changed while the program is running, and the program can be extended at run time.

The method area can also be garbage collected, but the condition is very strict, you must have no reference to the class, the details can refer to another article: Java performance optimization of the JVM GC (garbage collection Mechanism)-The news column

What does type information include?

1、类型的全名(The fully qualified name of the type)2、类型的父类型全名(除非没有父类型,或者父类型是java.lang.Object)(The fully qualified name of the typeís direct superclass)3、该类型是一个类还是接口(class or an interface)(Whether or not the type is a class )4、类型的修饰符(public,private,protected,static,final,volatile,transient等)(The typeís modifiers)5、所有父接口全名的列表(An ordered list of the fully qualified names of any direct superinterfaces)6、类型的字段信息(Field information)7、类型的方法信息(Method information)8、所有静态类变量(非常量)信息(All class (static) variables declared in the type, except constants)9、一个指向类加载器的引用(A reference to class ClassLoader)10、一个指向Class类的引用(A reference to class Class)11、基本类型的常量池(The constant pool for the type)

Methods List (method Tables)

To gain more efficient access to all data stored in the method area, in the method area, there is a data structure designed to speed up access, in addition to saving the above types of information: a list of methods. For each non-abstract class that is loaded, the Java Virtual machine generates a list of methods that hold references to all instance methods that the class might invoke, saving the methods that are called in the parent class.



Java Heap (JVM heap, heap)

When Java creates an instance object or array of a class, it allocates memory for the new object in the heap.

There is only one heap in the virtual machine, and all the threads in the program share it.

The heap occupies the most memory space.

The access type of the heap is pipe type, FIFO.

In a program run, you can dynamically allocate the heap's memory size.

Heap Memory resource recycling is given to the JVM GC for management, please refer to: Java Performance optimization JVM GC (garbage collection Mechanism)-Knowledge column



Java stack (JVM stack, stack)

Only the underlying data type is saved in the Java stack (see: Java Basic Data Type-four classes eight-the column) and a reference to a custom object, note that only the reference to the object and not the object itself Oh, the object is saved in the heap area.

Expand your knowledge: like String, Integer, Byte, short, Long, Character, Boolean these six are wrapper types, which are stored in the heap.

The access type of the stack is similar to that of a water cup, advanced back out.

The data inside the stack is automatically freed when it goes out of scope and is not managed by the JVM GC.

Each thread contains a stack area, and the data in each stack is private and the other stacks are inaccessible.

Each thread creates a stack of stacks, each containing several stack frames, each of which corresponds to each invocation of each method, with three parts per stack frame:

Local variable area (in-method basic type variable, variable object pointer)

Operand stack area (intermediate results produced during the execution of the method of storage)

Run Environment zone (dynamic connection, correct method returns information, exception snaps)



Local method Stack

The functionality of the local method stack is very similar to the JVM stack, which stores information such as local variable tables for native methods, operand stacks for local methods, and so on.

The access type of the stack is similar to that of a water cup, advanced back out.

The data inside the stack is automatically freed when it goes out of scope and is not managed by the JVM GC.

Each thread contains a stack area, and the data in each stack is private and the other stacks are inaccessible.

The local method stack is enabled when a program call or JVM calls the Local method interface (Native).

Local methods are not written in the Java language, such as native methods written in C, and local methods are not run by the JVM, so the operation of the local method is not managed by the JVM.

The HotSpot VM merges the local method stack with the JVM stack.

Program counter

In the JVM conceptual model, the bytecode interpreter works by changing the value of this counter to select the next byte-code instruction to execute. Basic functions such as branching, looping, jumping, exception handling, thread recovery, and so on, need to rely on this counter to complete.

The multithreading of the JVM is implemented by rotating threads and allocating processor execution time, so that each thread will have a separate program counter for the counter to return to the correct execution position after switching between the threads.

Program counters account for only a small chunk of memory space.

When a thread is executing a Java method, the program counter records the address of the executing JVM bytecode directive. If you are performing a Natvie (local method), then the value of this counter is empty (underfined).

Program counter this memory area is the only area in the JVM specification that does not specify any outofmemoryerror (out-of-memory errors).

JVM Execution Engine

The Java Virtual machine is the equivalent of a virtual "physical machine", both of which have code execution capabilities, the main difference is that the physical machine execution engine is directly based on the processor, hardware, instruction set and operating system level. The execution engine of the JVM is implemented by itself, so programmers can make their own instruction set and execution engine architecture, so they can execute instruction set formats that are not directly supported by the hardware.

A conceptual model of the virtual machine bytecode execution engine is developed in the JVM specification, which is called the uniform appearance of the JVM execution engine. In a JVM implementation, there may be two ways of doing it: interpreting execution (through the interpreter) and compiling execution (generating local code through the instant compiler). Some virtual machines take only one execution, while others may take two or even several different levels of compiler execution engines.

The input is the bytecode file, the process is the equivalent bytecode parsing process, the output is the execution results. At these three points, each JVM execution engine is consistent.

Local method Interface (JNI)

JNI is the abbreviation for Java Native Interface, which provides a number of APIs that enable the communication of Java and other languages (mainly C and C + +).

Application Scenarios for JNI

When we have some old libraries that have been written in C, it's a waste of time to migrate to Java, and JNI can support Java programs interacting with libraries written in C, so it doesn't have to be ported. Or, you can use JNI to interact with the hardware, the operating system, improve the performance of the program, and so on. One thing to note is the need to ensure that local code can work in any Java Virtual machine environment.

Side effects of JNI

Once you use the Jni,java program you will lose the two benefits of the Java platform:

1, the program is no longer cross-platform, to cross-platform, must be in a different system environment under the program to configure the local language section.

2, the program is no longer absolutely safe, improper use of local code may cause the entire program to crash. A common rule is that calling local methods should be concentrated in a few classes, which reduces the coupling between Java and other languages.

JVM constant Pool

The JVM Chang is also known as the run-time-constant pool, which is part of the method area. Used to hold various literal and symbolic references generated during compilation. Running a constant pool does not require that only the compiler generates the ability to enter, and the new constants can be put into the pool during the run, which is the String.intern () method used by developers.

The phrase "used to hold various literal and symbolic references generated during compilation" is visible, and the constant pool stores the reference to the object instead of the object itself.

The benefits of a constant pool

Chang is designed to avoid the frequent creation and destruction of objects that affect system performance, and it also implements the sharing of objects.

For example, a string constant pool: All string literals are placed in a constant pool during the compilation phase.

1. Save memory Space: If there is a corresponding string in the constant pool, then a reference to the object is returned, so that you do not have to create a new object again.

2. Save run Time: when comparing strings, = = faster than Equals (). For two reference variables, = = To determine whether the reference is equal, you can also determine whether the actual value is equal.

Meaning of the double equals sign (= =)

A double equals sign is used between the base data types, and the numeric value is compared.

A double equals sign is used between composite data types (classes), comparing whether the object's reference address is equal.

Eight basic types of wrapper classes and constant pools

The 7 wrapper classes of Byte, short, Integer, Long, Character, Boolean, and string each implement their own constant pool.

//例子:Integer i1 = 20;Integer i2 = 20;System.out.println(i1=i2);//输出TRUE

The 5 wrapper classes, Byte, short, Integer, Long, and character, create the cached data for the value [-128, 127] by default. When these 5 types of data are not within this interval, new objects are created, and the new objects are not placed in a constant pool.

Integercache.low =-128Integercache.high = 127PublicStaticIntegerValueOf(Inti {if  (i >= integercache. Low && i <= integercache high) return integercache.cache[i +  (- Integercache.return new integer (i               /span>                
//例子Integer i1 = 200;Integer i2 = 200;System.out.println(i1==i2);//返回FALSE

Float and double do not implement a constant pool.

String wrapper class and Constant pool

String str1 = "aaa";

When the above code is run, the JVM will look for the string constant pool to find the literal object "AAA" exists?

Present: The object's reference is returned to the variable str1.

Does not exist: a corresponding object is created in the heap, a reference to the created object is stored in the constant pool, and the reference is returned to the variable str1.

String str1 = "aaa";String str2 = "aaa";System.out.println(str1 == str2);//返回TRUE

Returns true because the variables str1 and str2 both point to the same object.

String str3 = new String("aaa");System.out.println(str1 == str3);//返回FALSE

When we use new to construct a string object, the new string object is created, regardless of whether there is a reference to the object with the same content in the string constant pool. Because two points to a different object, it returns false.

String.intern () method

For a string object created with new, you can use the Intern () method if you want to reference the object to a string constant pool.

After calling the Intern () method, check the string constant pool for a reference to this object and do the following:

Present: The direct return object is referenced to the variable.

Not present: Adds this object reference to the constant pool, and then returns the object reference to the variable.

String interns = str3.intern();System.out.println(interns == str1);//返回TRUE

Assuming that there are no more literal objects in a constant pool, how many objects are created below?

String str4 = "abc"+"efg";String str5 = "abcefg";System.out.println(str4 == str5);//返回TRUE

The answer is three. First: "ABC", First: "EFG", Third: "abc" + "EFG" ("ABCEFG")

String STR5 = "ABCEFG"; The code does not create an object, it finds a reference to "ABCEFG" from the constant pool, and all Str4 = = STR5 return True because they all point to the same object.

In what case will the string object reference be automatically added to the string constant pool?

//只有在这两种情况下会将对象引用自动加入到常量池String str1 = "aaa";String str2 = "aa"+"a";//其他方式下都不会将对象引用自动加入到常量池,如下:String str3 = new String("aaa");String str4 = New StringBuilder("aa").append("a").toString();StringBuilder sb = New StringBuilder();sb.append("aa");sb.append("a");String str5 = sb.toString();

Java Advanced Chapter (second, JVM memory model, memory management)

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.