PART1:JVM Memory Structure
The JVM defines a number of data regions that are used during the execution of a program. Some of the data in this area is created when the JVM is started and destroyed when the JVM exits. While the rest of the data depends on each thread, created when threads are created and destroyed when threads exit
The JVM memory structure can be 2 pieces:
Thread Private part:
1. Program Counter Register (Procedure counter): A small amount of memory space, the role of the current thread execution byte code of the line number indicator (similar to the traditional CPU model of the PC), the PC after each instruction executes the self-increment, Maintain the address of the next command to be executed. In the JVM model, the bytecode interpreter selects the next byte-code instruction that needs to be executed by changing the value of the PC, and the basic functions such as branching, looping, jumping, exception handling, thread recovery, and so on, are all dependent on the PC (Java method only, native method that counter value is undefined).
PS: In layman's terms, each thread has a program counter that tracks where the code is running.
2. Java stack (virtual machine stack): The virtual machine stack describes the memory model that the Java method executes: Each method is executed to create a stack frame to store information such as local variable tables, operand stacks, dynamic links, method exits, and so on. Each method is called to the return process, which corresponds to a stack frame in the virtual machine stack from the stack to the stack of the process (the VM provides a-XSS to specify the maximum stack space of the thread, which also directly determines the maximum depth of the function call).
PS: Is the thread execution method when the local variables and operations of each method, etc., the execution of the method is the process of entering the stack and out of the stack
3. Native Methods Stack (local method stack): Similar to Java stack, the difference is that Java stack is used for Java method service, and the local method stack is the Native method service. If a VM implementation uses the C-linkage model to support native calls, then the stack will be a C stack
PS: The principle is consistent with the Java stack, except that the native method of executing the JVM is used, the memory of native method stack
Thread Sharing section:
1. Heap (Java heap): Almost all object instances and arrays are allocated on the heap (except on stack allocations, scalar substitutions), so it is the largest chunk of memory managed by the VM and the main active area of the garbage collector. Because modern VMS use a generational collection algorithm, the Java heap can be subdivided from the GC perspective: The New Generation (Eden, from Survivor and to survivor) and the old age; From the memory allocation point of view, the thread-shared Java heap can also be divided into multiple thread-private allocation buffers (Tlab). The purpose of further partitioning is to better reclaim memory and to allocate memory more quickly.
PS: An area that can be understood to hold each object and array
2. Method Area: The Permanent generation (Permanent Generation), which we often call, is used to store data such as class information, constants, static variables, and code compiled by the immediate compiler, which are loaded by the JVM. The hotspot VM extends the GC generational collection to the method area, which uses the Java heap's permanent generation to implement the method area so that the hotspot garbage collector can manage this part of the memory like the Java heap without having to develop a dedicated memory manager for the method area ( The primary goal of the memory recovery for a permanent band is to recycle the constant pool and unload the type, so the benefits are generally small)
PS: The area of a static variable that can be understood as the storage of some constants of a class
The life cycle of a thread-private memory area is created as the thread is created, dies as the thread dies, does not need to be garbage collected, and the memory area of the thread share (heap and method area) is created/destroyed with the virtual machine's startup/shutdown. So, to do garbage collection , Specific garbage collection principles will be explained in the next section (ref.: http://www.cnblogs.com/zwt1990/p/8322376.html)
Part2: JVM class loading mechanism
Overview: To execute a class file, the JVM needs to be loaded by the ClassLoader, loading the files into the virtual machine's method area, and storing the data accordingly, depending on the format of the class file. When an object needs to be produced, the corresponding class information is obtained from the method area and the object is established in the heap.
Loading process (e.g.)
1. Loading: Find and import class files;
2. Connection:
(1) Check: Check the correctness of the loaded class file data;
(2) Preparation: The Prep phase allocates memory for a static variable of a class and initializes it to its default value, which is allocated in the method area. The prepare phase does not allocate memory for instance variables in the class, and instance variables are allocated in the Java heap along with the objects as they are instantiated.
(3) parsing: Converting a symbolic reference to a direct reference (this step is optional)
3. Initialization: Class initialization is the last step of the class loading process, and the rest of the actions are completely dominated and controlled by the virtual machine in addition to the user application being able to participate through the custom class loader during the load phase. In the initialization phase, the Java program code defined in the class is actually started.
Where the order of the five stages of loading, validating, preparing, initializing, and unloading is determined, the loading process of the class must be "started" in this order (only the beginning, not the execution or the end, as these phases are usually cross-mixed, It is common to invoke or activate another phase during one phase of execution, while the parsing phase is not necessarily (it can be started after the initialization phase in some cases, in order to support runtime bindings for the Java language.)
A few moments of class loading
1. Creating an instance of a class
2. Accessing static variables of a class
3. Accessing static methods of a class
4. Reflection (Class.forName ("My.xyz.Test") classroader)
5. When initializing a class and discovering that its parent class has not yet been initialized, start the initialization of the parent class
6. When the virtual machine starts, the class that defines the main () method is initialized first.
Parental delegation mode
When the ClassLoader needs to load the class, ask its parent (that is, the previous loader) to load it in its search path, and if not, search for the class in its own search path. This order is actually the top-down search at the loader level, because the loader must ensure that the underlying class is loaded. There is a security concern about this mechanism: if someone loads a maliciously rewritten base class into the JVM, the delegate model mechanism searches its parent classloader, and the discovery already exists does not load.
1.Bootstrap class loader (boot class loader)
Responsible for loading the Java Core Class library. In the Jre\lib directory, including the Rt.jar (Java base Class library), these
Are the core class libraries of Java. And this loader is written in C, so in Java programs it gets
Less than that.
2.Extension class loader (extension ClassLoader)
The jar package that is responsible for loading the extended functionality under the Java platform, which is in the Jre\lib\ext directory. This load
Written by the Java language.
3.System class Loader (System loader)
Responsible for loading all class libraries under the Classpath directory, the class file under the Classpath directory is generally
We wrote the Java file after compiling it. And this loader is written in the Java language.
the meaning of the delegation mechanism-to prevent multiple copies of the same bytecode from appearing in memory
For example, two classes A and b all load the system class:
- If you load yourself without a delegate, class A loads a copy of the system bytecode, and then class B loads a copy of the system bytecode so that two copies of the system bytecode are present in memory .
- If you use a delegate mechanism, you will recursively find the parent class, which is preferred to try to load with bootstrap if it is not found again. The system here can be found in bootstrap and then loaded, and if Class B also loads the system at this point, starting with Bootstrap, Bootstrap found that the system has been loaded and returned directly to the in-memory system without reloading , so there is only one copy of the system's bytecode in memory.
See an example
Lass SingleTon {Private StaticSingleTon SingleTon =NewSingleTon (); Public Static intCount1; Public Static intCount2 = 0; PrivateSingleTon () {count1++; Count2++; } Public StaticSingleTon getinstance () {returnSingleTon; } } Public classTest { Public Static voidMain (string[] args) {SingleTon SingleTon=singleton.getinstance (); System.out.println ("Count1=" +singleton.count1); System.out.println ("Count2=" +Singleton.count2); } }
The final output is:
Count1=1
Count2=0
We analyze from the loading mechanism of the class:
1: When executing the Main method, the Singleton.getinstance () method will load the class, and during the class load preparation phase, the JVM allocates memory for the static variable and initializes the default value (the code above: SingleTon = null; count1 =0 ; count2=0;)
2: After the preparation phase, into the initialization phase, the symbolic reference within the constant pool is replaced by the process of direct referencing (appeal code: Assigning a value to a static variable singleton=new singleTon (), performing a construction method, count1=1;count2= 1; Continue assigning values to static variables: Count1, count2=0)
Based on class loading and parental delegation mode we get one of the following rules
Code Execution Order: static variable, static initialization block) –> (variable, initialization block) –> constructor; If there is a parent class, the order is: Parent class static method –> Subclass static method –> Parent class construction Method---subclass constructor method
Summary: JVM memory structure and class loading mechanism we are mainly to understand how its classes are stored and the process of loading (parental delegation mode)
Java Review notes: Memory Structure and class loading