One, what is a virtual machine, what is a Java Virtual Machine 1.1 virtual machine
definition: software that simulates a computer architecture and executes a specific set of instructions
Classification System virtual machine (vmware,virtual box, etc.), process virtual machine
1) Process Virtual machine
Features: does not fully simulate an operating system environment, only provides a specific instruction set of the operating environment
Example: JVM, Adobe Flash, FC simulator
2) Advanced Language virtual machine
feature: further limit the scope of a particular instruction set to a high-level language.
One of the process virtual machines, such as the JVM,. NET CLR, P-code
3) Java language virtual machine
A high-level language virtual machine that executes the Java language. Java language virtual machines are not necessarily called JVMs, for example: Apache Harmony
4) Java Virtual machine
- Java-language virtual machines that must pass Java TCK compatibility tests to be called Java virtual machines
- Java virtual machines are not necessarily executing Java programs, and Java virtual machines are related to the Java compiled class file.
- The industry's three commercial jvm:orcale hotspots, Oracle JRockit VMS, IBM J9 VMS
1.2 Conceptual models and concrete implementations
Shared design, private implementation
The Java Virtual Machine specification declares a conceptual model that does not constrain the implementation of a virtual machine, and only requires that the virtual machine's implementation be as external as the canonical description.
For example, the specification specifies the memory of the objects in the Java heap and requires the virtual machine to automatically complete garbage collection, which can be different, but the effect needs to be the same.
1.3java Virtual Runtime Data area
- The Java Virtual Machine specification defines a number of different types of storage areas that are used during program runs.
- Some zones are shared globally, and are created as virtual machines are started and destroyed as virtual machines exit. Some areas are thread-private and are created and destroyed as threads start and end.
- is a common memory area conceptual model for all Java virtual machines
Division of data regions at run time:
- Program counter
- Java heap
- Java Virtual Machine stack
- Local method Stack
- Method area
which
The method area and the heap are all threads that share the data area.
The virtual machine stack, the local method stack, and the program counter are thread-private.
Second, the program counter Area (PC)
- is the smallest chunk of all Java runtime memory areas,
- Function: Can be seen as the line number indicator of the byte code executed by the current thread. (Can be seen as a pointer to the current line of code that is running the byte code)
- Note: If you are executing a Java method, the PC logs the address of the virtual machine bytecode instruction being executed, or the PC is empty if the native method is being executed.
- This memory area is the only area in the Java Virtual Machine specification that does not stipulate any outofmemoryerror conditions.
Java Virtual machine stack and local method stack 3.1 The concept and characteristics of Java Virtual machine stack
- Thread private, life cycle and thread same
The Java Virtual machine stack describes the memory conceptual model at the time of the Java method execution, where each method creates a stack frame (the operand stack, local variable table, method exit, dynamic connection, and so on) that is used to create the method. Each method in the call and the end of the process, corresponding to a stack frame in the virtual machine into the stack and the process of the stack.
- Last in, first out (LIFO) stacks
The method of follow-up will be done first.
- Storage stack frames, supporting the invocation, execution, and exit of Java methods
- OutOfMemoryError and Stackoverflowerror exceptions may occur
A thread request with a stack depth greater than the maximum allowable depth of the Java Virtual machine will throw a Stackoverflowerror exception.
A OutOfMemoryError exception is thrown when a Java virtual machine is designed to be dynamically extensible and cannot be applied to enough memory when it is dynamically extended.
3.2 Concepts and characteristics of the local method stack
- Thread Private
- Last in, first out (LIFO) stacks
- The function is to support the invocation, execution, and exit of the native method.
- OutOfMemoryError and Stackoverflowerror exceptions may occur
- Some virtual machines, such as hotspot, combine the Java Virtual machine stack and the local method stack to implement
3.3 Concept and characteristics of stack frames
- The content stored in the Java Virtual machine stack, which is used to store data and data structures for partial process results, and is also used to handle dynamic links, methods, and exception dispatch
- A complete stack frame contains: local variable table, operand stack, dynamic link information, method normal completion and exception completion information
When compiling program code, the size of the local variable table required by the stack frame and the depth of the operand stack are fully determined during compilation, and the Java virtual Opportunity is fully written in the code table of the class file. Therefore, the amount of memory that a stack frame needs to allocate is not affected by the variable data during program run, but only by the specific Java virtual machine.
In a thread the call chain of the method may be very long, many methods may be in the same state of execution, for the execution engine, in the active thread, only the stack frame located at the top of the Java Virtual machine stack is valid, this stack frame is called the current stack frame, and the method associated with this stack frame is called the current method. All bytecode instructions executed in the virtual machine are for the current method and the current stack frame operation.
Local variable table concepts and features
definition: A storage space for a set of variable values for storing methods, parameters, and local variables defined inside a method, and so on.
When the Java compiler compiles a class file, it has determined the maximum capacity of the local variable table required by the method, and the local variable table is the smallest unit in slots (slots). The Java Virtual Machine specification does not explicitly specify the size of a slot's memory footprint, but simply describes the types that any slot can store.
- Consists of several slots, the length of which is determined by the compilation period
- A single slot can store data of a type of Boolean, Byte, char, short, float, reference, and ReturnAddress, and two slots can store data of a type long or double.
Where the reference type represents a reference to an object instance, the instance data of the variable can be found indirectly or directly through reference, and the type data of the object can be found directly or indirectly by reference, and ReturnAddress has been deprecated.
- Local variable tables are used for inter-method parameter passing, as well as for storing values and references to objects of the underlying data type during method execution.
In method execution, if the method being called is an instance method, the No. 0 slot of the local variable of this method will be referenced by default as an instance of storing this method, in which the implicit parameter can be accessed through the keyword diss two. The remaining method parameters are arranged in the order of the parameter table, occupying a local variable tablespace starting at 1. After the parameter table is allocated, the rest of the local variable slots are allocated according to the order of the local variables in the method table and their scope, in order to save space on the stack frame, the slots in the local variable table can be reused.
Concept and characteristics of the operand stack
- An element of a single operand stack, called entry
- LIFO Stack, composed of several entry, the maximum stack depth of the operand stack is determined during compilation
- A single entry can store values for any data type defined in a Java virtual machine, including the long and double types, but the entry depth of the stored long and double types is 2, and the other types have a depth of 1.
- During the execution of the method, the operand stack is used to store the calculated parameters and the results of the calculation; At the time of the method invocation, the operand stack is also prepared to prepare the parameters for the calling method and the return result when exiting.
When a method is just beginning to execute, this method's operand stack is empty, in the process of executing the method will encounter various bytecode instructions to the Operation Stack to write and extract the content corresponding to the stack of stacks and the operation of the stack.
3.4 Local variable table and operand stack instances
Enter in cmd
copy con Test.java
Then enter the program:
public class Test{ public int calc(){ int a =100; int b =200; int c =300; return (a+b)*c; }}
and then compile
javac Test.java
To see the bytecode again:
javap -verbose Test.class
Get:
0: bipush 100 //把100入栈到操作数栈的栈顶 2: istore_1 //把操作数栈顶的元素出栈并把此元素存储在局部变量表中的1号Slot 3: sipush 200 6: istore_2 7: sipush 300 10: istore_3 11: iload_1 //将局变量表中的为1号的操作数入栈到操作数栈栈顶 12: iload_2 //将局变量表中的为2号的操作数入栈到操作数栈栈顶 13: iadd //将操作数栈栈顶的两个元素出栈,然后相加入栈 14: iload_3 15: imul 16: ireturn
3.5 Memory Exception Instances
Note: in idea, you can set the Java Virtual machine stack by setting the run-------------and the configuration--and the VM options Size add: -xss128k
.
Stackoverflowerror Exception
public class javavmstacksof {private int stacklength = 1 ; public void stackleak () {stacklength++; stackleak (); } public static void main (string[] args) {javavmstacksof oom = new javavmstacksof (); try {Oom. stackleak (); }catch (Throwable e) {system.. println ( "Length" + oom. stacklength ); throw e; } }}
OutOfMemoryError exception
Public classJavavmstackoom {Private void Dontstop(){ while(true){ } } Public void Stackleakthread(){ while(true) {Thread thread =NewThread (NewRunnable () {@Override Public void Run() {Dontstop(); } }); Thread.Start(); } } Public Static void Main(string[] args) {Javavmstackoom Oom =New Javavmstackoom(); Oom.Stackleakthread(); }}
Iv. the Java heap 4.1 Java heap Concept
Characteristics:
- Global share
- Typically the largest chunk of memory in a Java virtual machine
- function as the primary store for Java objects
- JVMs explicitly requires the region to implement automatic memory management, known as GC, which does not restrict which algorithms and technologies are used to implement
- May appear outofmemoryerror
The implementation of the Java heap can be fixed-size or dynamically extensible, and now mainstream virtual machines are implemented in a scalable way to implement the Java heap, which throws this OOM exception when no memory is available in the Java heap.
Partitioning method:
- Tlab:java the objects in the heap are shared by the thread, so there is a competition for the data, and in order to avoid this competition, the Java Virtual machine is likely to divide the heap into several thread-private memory buffers based on each thread, called Tlab, which is the thread-local allocation cache. Each thread then allocates objects in its own tlab, locks only when Tlab is exhausted, and allocates new Tlab memory to the Java heap. -XMX512M (set maximum)-xms16m (set minimum)
- New generation, the old age, the permanent generation, which is based on a GC recovery of memory algorithm to be divided.
4.2 Stacks and heaps
The association process from stack to heap:
The second way of implementation:
Contrast:
In the second way, the address of a stable handle is stored in the reference, when the object is moved (the object is often moved, garbage collection is moved), only the pointer to the object type data in the handle pool is changed, and the reference does not change.
The first way, faster, compares the way the handle is used, saves the pointer overhead, and reference directly points to the object's instance data.
4.3 java heap Memory exception combat
Exceptions that may occur:
- If the actual required heap exceeds the maximum capacity that the automatic memory management system can provide, the Java virtual machine will throw an Oom exception. The Java heap is the region with the greatest probability of memory anomalies.
An Oom instance appears as follows:
Constantly create objects and ensure that they are not recycled.
publicclass javaHeapOOM { staticclass OOMObject{ } publicstaticvoidmain(String[] args) { new ArrayList<>(); while(true){ list.add(newOOMObject()); } }}
The concept of method area and run-time constant pool 5.1 method area
- Global share
- The function is to store the structure information of the Java class
- JVMs does not require automatic memory management for this zone, but it is essential to automatically manage memory for that zone
- OutOfMemoryError exceptions may occur
Attention:
class instance data and class type information
Instance data refers to the various instance objects defined in a class and their values, while type information refers to constants defined in class code, static variables, various methods declared in a class, fields, and so on, and also includes data generated by the immediate compiler compilation.
5.2 Concept of running a constant-rate pool
- Global share
- is part of the method area
- The function is to store symbolic information in a constant pool of Java class files
The change of 5.3 HotSpot method area Realization
Permanent generation and Method area
- In jdk1.2~jdk1.6, Hotspot uses a permanent generation implementation method area
- At the beginning of JDK7, hotspot began to remove the permanent generation plan
- The symbol table is moved to the native heap
- string constants and static references to classes are moved to the Java heap
- At the beginning of the JDK8, the permanent generation has been replaced by the meta-space (METASAPCE)
5.4 Method Area Memory Exception combat
The abnormal differences caused by the process of permanent generation change:
Example 1:
public Runtimeconstantpoolchange {public static void main (string[] args) {String str1 = new stringbuild ER ( "HPTJ" ). append ( "ZZJ" ). tostring (); System. out . println (str1. intern () = = str1); String str2 = new StringBuilder ( "ja" ). append ( "va" ). tostring (); System. out . println (str2. intern () = = str2); }}
Intern method: Periodic maintenance of a string pool, if the string has this string, it will return the address of the constant in the pool, if the string does not have the required constant, the JVM will first add the string to the string constant pool, and then return the address of the string.
The string constant pool is moved to the heap after java1.7 begins.
When running with jdk1.6, false occurs because Str1.intern returns an address in a constant pool, and str1 native addresses are not identical in the heap.
When running with jdk1.7, true false occurs because The Str1.intern and heap are the addresses in the heap, and the HPTJZZJ string does not appear in the stack, it is added to the constant pool in the heap, and the address in the heap is returned to the same address, and the Java string already exists in the heap constant pool, and a new object is created after new, so it is Not equal.
Six, Direct memory 6.1 the concept and characteristics of direct memory
- Not a standard Java Runtime memory area defined by JVMs
- NiO added with JDK1.4 is introduced to avoid performance loss from replicating data back and forth in the Java heap and the native heap
- Global share
- Can be automatically managed, but there may be some rudimentary means of detection
- Outofmempryerror exceptions may occur
Java Memory Management