Today is nothing to do, look at the memory model in Java and the principle of garbage collection mechanism, on this aspect of knowledge, the online has a lot of readily available information for our reference, but the knowledge is relatively miscellaneous, in this part of the knowledge Point has a book to recommend:"in-depth understanding of Java Virtual Machine" , it is now the second edition. This book starts from scratch. The model of the whole Java virtual machine and the Java class file structure, loading mechanism and so on are introduced in detail. Most of the knowledge here can be found in this book, of course, I am mainly or learn from this book a lot of content. Here is not much to say, enter the topic.
First, consider the memory model diagram in Java:
First, the program counter (PC)
Program Counter Register is a small amount of memory space, which can be seen as the current thread execution of the bytecode of the line number indicator, the bytecode interpreter works by changing the value of this counter to remove a need to execute the bytecode instruction, branch, jump, loop, Basic functions such as exception handling, thread recovery, and so on, require this counter to complete
Note: Program counters are thread-private and each thread will have a separate program counter
Second, Java stack (virtual machine stack)
The Java stack is the memory model that the method executes in Java, and each method creates a stack frame at the same time (about the stack frame), which is used to store the local variable table, the operand stack, the dynamic link, the method exit, and so on, each method from the call until the completion of the process of execution, Corresponds to a stack frame in the virtual machine stack into the stack to the process.
Note: The Java stack is also thread-private.
exception probability: There are two exceptions to the stack: if the thread requests a stack depth greater than the stack's allowable depth, the Stackoverflowerror exception will be thrown if the virtual Machine Stack can be dynamically extended, when the extension cannot request enough memory, will throw OutOfMemoryError exception
Concept of stack frame:
Stack frames are used to support the data structure of a virtual machine for method invocation and execution.
1) local Variable table
A local Variable table is a set of variable value storage spaces that are used to store method parameters and local variables defined inside the method. The capacity of the local variable table is the smallest unit in the variable slot (Variable slot, lower slot). A slot can hold a 32-bit data type, with 32-bit data types within Java (Boolean, Byte, char, short, int, float, reference[3], and ReturnAddress 8 types, for A 64-bit data type in which the virtual opportunity assigns two contiguous slot spaces (long double) in a high-aligned manner.
2) Operand stack
The operand stack (Operand stack) is also often referred to as the Operation Stack, which is a post-in first-out (last-Out,lifo) stack, and when a method has just been executed, the operand stack of this method is empty, during the execution of the method, There will be various bytecode instructions to write to the operand stack and extract the content, that is, the stack/stack operation, for example, when doing arithmetic operations by the operand stack, or when the other method is called by the operand stack to pass the argument.
For example: the byte code instruction of the integer wig Iadd the two elements closest to the top of the stack at run time in the operand stack have been stored in two int type values when performing this instruction, the two int values are stacked and added, and the result of the addition is then put into the stack.
3) method return address
After a method has started executing, there are only two ways to exit this method. The first is that the execution engine encounters a bytecode instruction returned by either method, at which point the return value may be passed to the method caller of the upper layer (the method calling the current method is called the caller), and whether the type of the return value and the return value will be determined based on what method the return instruction is encountered, which is called Normal completion exit (normal Method invocation completion). Another way to exit is to encounter an exception during the execution of the method, and the exception is not handled in the method body, whether it is an exception generated inside the Java virtual machine, or an exception that is generated in code using the Athrow bytecode directive, as long as no matching exception handler is found in the exception table of this method. Causes the method to exit, the way the exit method is called the exception completion exit (abrupt invocation completion). A method exits with an exception completion exit, and is not given any return value to its upper-level caller.
4) Additional Information
The virtual machine specification allows specific virtual machine implementations to add information that is not described in the specification to the stack frame, such as debugging-related information, which is entirely dependent on the specific virtual machine implementation, which is no longer detailed here. In the actual development, the dynamic connection, the method return address and other additional information are generally classified as a class, called the stack frame information.
Third, local method stack
The role of the local method stack with the Java stack is very similar, and the difference between them is simply the Java stack execution Java method, the local method stack executes the local method.
Note: The local method stack is also thread private
Exception probability: As with the Java stack, stackoverflowerror and Outofmemeryerror exceptions can be thrown
IV. Java HEAP
For most applications, the Java heap is the largest piece of memory managed by a Java virtual machine and is created when the virtual machine is started. The only purpose of this memory area is to hold object instances, where almost all object instances are allocated memory, and of course the Java heap is the main area of garbage collector management when we talk about garbage collector content later.
Note: The heap is thread-shared
Exception probability: A Outofmemeryerror exception is thrown if there is no memory in the heap to complete the instance assignment and the heap cannot be extended again
V. Method area
The method area is used to store data such as the class information that has been loaded by the virtual machine, constants, static constants, immediate compiler-compiled code, and so on.
Note: The method area and heap are thread-shared
Exception probability: A Outofmemeryerror exception is thrown when the method area does not meet the memory allocation requirements
1) Run the constant-rate pool
The run-time pool is part of the method area, and in addition to the description of the class's version, field, method, interface, and so on, there is a constant pool that holds the various literal and symbolic references generated by the compiler, which is stored in the runtime exception constant pool of the method area after the ClassLoader.
The above describes the Java memory of several modules related concepts, in fact, we need to know this knowledge, the main purpose is not to write those oom code in the project, because if we know the memory model, even if there is an oom problem in the code, we can locate where the problem.
Let's take a look at the memory overflow exception caused by several memory modules mentioned above:
(This is also often asked during an interview: like asking you to write a code that lets a heap of memory overflow, or if you want to change the heap size)
First, heap overflow
public class Heapoom {static Class oomobject{}/** * @param args */public static void main (string[] args) {List<oomobjec t> list = new arraylist<oomobject> (), while (true) {List.add (New Oomobject ());}}}
we see that the heap is primarily a storage object, so if we want the heap to appear oom, we can open a dead loop, and then create a new object. Then, turn the size of the heap down a little bit.
Plus JVM Parameters
-VERBOSE:GC -xms10m-xmx10m -xx:+printgcdetails-xx:survivorratio=8-xx:+heapdumponoutofmemoryerror,
will be able to quote the Oom soon:
Exception in thread "main" Java.lang.OutOfMemoryError:Java heap space
Second, Stack Overflow
Package Com.cutesource;public class Stackoom {/** * @param args */private int stacklength = 1;public void Stackleak () {Stac Klength++;stackleak ();} public static void Main (string[] args) throws throwable{//TODO auto-generated method Stubstackoom oom = new Stackoom (); TR Y{oom.stackleak ();} catch (Throwable err) {System.out.println ("Stack Length:" + oom.stacklength); throw err;}}}
we know the amount of space that is required to execute the method stored in the stack, so we can iterate over the next loop so that the method stack will appear with an oom exception.
Set JVM parameters:-xss128k, report exception:
Exception in thread "main" Java.lang.StackOverflowError
Print out the stack length:1007, as you can see, the 128k stack capacity on my machine can carry a method call with a depth of 1007. Of course, this kind of error is seldom seen, usually only in the infinite loop recursion, in addition, too many threads will occupy the stack area:
Package Com.cutesource;public class Stackoom {/** * @param args */private int stacklength = 1;private void Dontstop () {Whil E (True) {try{thread.sleep (1000);} catch (Exception err) {}}}public void Stackleakbythread () {while (true) {thread t = new Thread (new Runnable () {@ overridepublic void Run () {//TODO auto-generated method Stubdontstop ();}); T.start (); stacklength++;}} public static void Main (string[] args) throws throwable{//TODO auto-generated method Stubstackoom oom = new Stackoom (); TR Y{oom.stackleakbythread ();} catch (Throwable err) {System.out.println ("Stack Length:" + oom.stacklength); throw err;}}}
The overflow of this stack is the two exceptions to the stack we have mentioned above.
Report exception:Exception in thread "main" java.lang.OutOfMemoryError:unable to create new native thread
Third, method area overflow
public class Methodareaoom {static Class oomojbect{}/** * @param args */public static void main (string[] args) {//TODO Au To-generated method Stubwhile (true) {enhancer eh = new enhancer (); Eh.setsuperclass (Oomojbect.class); Eh.setusecache ( FALSE); Eh.setcallback (new Methodinterceptor () {@Overridepublic object Intercept (object arg0, Method arg1,object[] Arg2 , Methodproxy Arg3) throws Throwable {//TODO auto-generated method Stubreturn arg3.invokesuper (arg0, arg2);}}); Eh.create ();}}}
we know that the method area is the information that holds some classes, so we can load the class with an infinite loop, so that the oom exception for the method area occurs.
Manually adjust the stack size by a small point
Add the JVM parameter:-xx:permsize=10m-xx:maxpermsize=10m, the following exception will be reported after running:
Exception in thread "main" Java.lang.OutOfMemoryError:PermGen space
IV. Chang Overflow
public class Constantoom {/** * @param args */public static void main (string[] args) {//TODO auto-generated method Stubli st<string> list = new arraylist<string> (), int i=0;while (TRUE) {List.add (string.valueof (i++). Intern ());}}}
we know that constant pools hold constants in the process of running, and we know that the Intern method of the string type is to put the value of strings into a constant pool. So it's possible to open a dead loop. Put the value of the string in the constant pool, so that the constant pool will have an oom exception. Because the constant pool itself is part of the method area, we can also manually adjust the size of the stack.
Summary : The above is just a macro view of the memory model, specific information about each area in memory, you can read the beginning of the very good book. Of course, we can be divided into four modules when we study Java: Java API, Java Virtual machine (memory model and garbage collector), Java class file, design pattern, knowledge about API We use more in the process of work, and this part of the content is completely rely on the degree of use, You use more, the API you naturally know. The knowledge of Java virtual machines and Java class files may not be available at work, but this knowledge will give you a better understanding of the overall Java architecture. As for design patterns This is the process of cultivation and the most difficult process. Have to slowly understand the strength of the place.
---memory model of Java Virtual Machine parsing chapter