---memory model of Java Virtual Machine parsing chapter

Source: Internet
Author: User

Today is nothing to do, look at the memory model in Java and the principle of garbage collection mechanism. On this aspect of knowledge, there are already a lot of ready-made information on the Internet for our reference, but the knowledge is relatively miscellaneous, in this part of the knowledge point of a book has to recommend: "In-depth understanding of Java Virtual Machine", is now the second edition. This book starts from the beginning. 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 the book's very much content. The following is not much to say. Go to the theme.


First, consider the memory model diagram in Java:

First, the program counter (PC)

Program Counter Register is a small memory space that can be seen as the line number indicator of the byte code running by the current thread, while the bytecode interpreter works by changing the value of this counter to remove a required bytecode instruction, branch, jump, loop, This counter is required for basic functions like exception handling, thread recovery, etc.

Note: Program counters are thread-private. Each thread will have a separate program counter


Second, Java stack (virtual machine stack)

The Java stack is the memory model in which the methods in Java run, and each method creates a stack frame at the same time (about the stack frame). This stack frame is used to store local variable tables, operand stacks, dynamic links, method exits and other information, each method from the call until the completion of the process, corresponding to a stack frame in the virtual machine stack into the stack of the process.

Note: The Java stack is also thread-private.

exception probability: There are two exceptions to the stack: Assume that the stack depth requested by the thread is greater than the depth agreed to by the stack. The Stackoverflowerror exception will be thrown, assuming that the virtual machine stack can be dynamically extended and cannot be applied to enough memory at the time of expansion , and the OutOfMemoryError exception will be thrown


Concept of stack frame:

Stack frames are used to support the data structures that the virtual machine makes method calls and runs.


1) local Variable table

A local Variable table is a set of variable value storage spaces. A local variable that holds the method parameters and the internal definition of the method. The capacity of the local variable table is in the variable slot (Variable slot. Slot) is the smallest unit. 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 when a method is just running. The operand stack for this method is empty. During the operation of the method, various bytecode instructions are written to and extracted from the operand stack, that is, the stack/stack operation, for example. The arithmetic operation is done by the operand stack, or when the other method is called by the operand stack to pass the parameter.

For example : integer wig byte code directive iadd at run time the operand stack is closest to the top of the stack two elements have been stored in two int type values, when running this directive. The two int values are stacked and added, and the result of the addition is added to the stack.


3) method return address

Once a method has started running, there are only two ways to exit this method.

The first way is to run the engine to encounter a random method to return the bytecode directive, this time there may be a return value passed to the upper layer of the Method caller (the method calling the current method is called the caller), whether there is a return value and the type of the return value will be determined by what method returned instruction, such an exit method is called Normal complete exit (normal Method invocation completion). The second type of exit is. Encountered an exception during the operation of the method, and the exception is not processed in the method body, whether it is generated inside the Java Virtual Machine exception, or the code in the use of Athrow bytecode instructions generated by the exception, only in the exception table of this method does not search for a matching exception handler, will cause the method to exit, The way to exit this method is known as an abnormal completion exit (abrupt invocation completion). A method that exits with an abnormal exit is not given to its upper-level caller regardless of the return value.


4) Additional Information

The virtual machine specification agrees with the detailed virtual machine implementation to add some specifications that do not describe the information described in the stack frame, such as debugging-related information, this part of the information is entirely dependent on the detailed virtual machine implementation, here is no longer detailed. In the actual development, the dynamic connection, the method return address and other additional information is usually classified as a class, called the stack frame information.


Third, local method stack

The role of the local method stack is very similar to the Java stack, where the difference is simply that the Java stack is running Java methods, and the local method stack is running local methods.

Note: The local method stack is also thread private

Exception possibility: Same as Java stack. May throw Stackoverflowerror and Outofmemeryerror exceptions


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, almost all object instances are allocated memory here, of course, when we talk about the contents of the garbage collector, the Java heap is actually the main area of garbage collector management.

Note: The heap is thread-shared

Exception probability: A Outofmemeryerror exception is thrown if there is no memory-complete instance allocation in the heap and the heap cannot be extended.


V. Method area

The method area is used to store data such as class information, constants, static constants, and code compiled by the immediate compiler, which have been loaded into the virtual aircraft.

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

Run a constant pool is part of the method area, in addition to the class file has the type of version number, field, method, interface and other descriptive information, the other information is a const pool, used to hold the compiler generated a variety of literal and symbolic references, which will enter the method area after the class loader run-time pool storage.


The above describes the concept of several modules of Java memory, in fact we need to know this knowledge. The basic goal is not to write the Oom code in the project, since we assume we know the memory model. Even if there is an oom problem in the code, we can pinpoint where the problem is.


Here's a look at the memory overflow exception caused by several memory modules mentioned above:

(This is also often asked during an interview: for example, to write a code that lets a heap of memory overflow, or to ask you to assume a change in 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 let's assume that we want the heap to appear oom. The ability to open a dead loop and then produce a new object is possible.

Then, turn the size of the heap down a little bit.

Plus the JVM's number of references

-VERBOSE:GC -xms10m-xmx10m -xx:+printgcdetails-xx:survivorratio=8-xx:+heapdumponoutofmemoryerror.

Can be very express out of Oom:

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 space that is required to run the method stored in the stack, so we are able to iterate over the next loop so that the method stack will have an oom exception.

Set JVM parameters:-xss128k. To report an exception:

Exception in thread "main" Java.lang.StackOverflowError

Print out the stack length:1007. Can be seen here. The 128k stack capacity on my machine can carry a method call with a depth of 1007.

Of course, it is rare to report such a mistake, and it is generally only possible to have recursive recursion in infinite loops. In addition, too many threads can fill up 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 class with classes loaded in an infinite loop, so that the oom exception for the method area occurs.

Manually adjust the stack size by a small point

Plus JVM parameters:-xx:permsize=10m-xx:maxpermsize=10m, which will be reported after running for example the following exception:

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 pooling is the constant in the run, and the same time we know that the Intern method of the string type is to put the value of strings into the constant pool. So it can open a dead loop. Places the value of a string in a constant pool. This way, the constant pool will have an oom exception. Since 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 macroscopic view of the memory model, detailed information about each area in memory, to read the very good book at the beginning.

Of course, when we learn Java, we can be divided into four modules: 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 entirely by use, you use more, API you naturally know. 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 entire architecture of Java. As for design patterns This is the process of cultivation and the most difficult process. Have to slowly understand the strength of the place.






Java Virtual Machine Parsing Chapter---memory model

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.