http://lovnet.iteye.com/blog/1825324
First, JVM memory area partition most JVMs divide the memory area into
Method Area (non-heap),
Heap,
Program Counter Register,
Java Method Stack,native method StackAnd
Direct Memomry(Note that Directory memory is not part of the storage area managed by the JVM.) The first three are generally translated as: Method area, heap, program counter. But different information and books on the latter three of the Chinese translation is not the same, here they are translated:
Java method Stack, native method stack, and direct memory area。 For different JVMs, memory partitioning may vary, such as hot Spot combining the Java method stack with the native method stack, which we can collectively call
Method Stack。 First, we are familiar with the working process of a generic Java program. A Java source program file, which is compiled into a bytecode file (with the class extension), then informs the JVM program of the running portal, which is then loaded by the JVM through the bytecode interpreter. So how does the program get involved in each memory area after it starts running? In summary, the JVM allocates a program counter, Java method stack, and native method stack for each thread it encounters. When the thread terminates, the memory space occupied by both is also freed. Stacks are stored in the stack frame, it can be said that each stack frame corresponding to a "running scene." In each "Running scene", if a local object appears, its instance data is saved in the heap, and the class data is saved in the method area. Ii. directives, methods, and properties before we talk about the parts, the first thing we need to figure out is
What is data and what is an instruction。 And then we need to figure out
object methods and properties of the objectWhere they are stored separately. 1) The method itself is an instruction
Operation CodePart, stored in a stack; 2) method internal variables as directives
Number of operandssection, followed by the opcode of the instruction, is saved in the stack (in fact, the simple type is saved in the stack, the object type holds the address in the stack, the value is stored in the heap), and the instruction opcode and the instruction operand above constitute the complete Java instruction. 3) Object
Exampleincluding its
Property ValueAs data, it is saved in the data area heap. Non-static object properties are persisted as part of the object instance in the heap, and the object instance must be accessed through an address pointer saved in the stack. Therefore, the ability to access an object instance and its non-static property values depends entirely on the availability of an object instance's address pointer in the stack. The difference between a non-static method and a static method is that there is a significant difference between a non-static method and a static one: a non-static method has an implicit incoming parameter, which is given to it by the JVM, regardless of how we write the code, the implied argument is
The address pointer of the object instance in the stack。 Therefore, a non-static method (the instruction code in the stack) can always find its own private data (object property values in the heap). Of course, a non-static method must also obtain the implied argument, so a non-static method must be called before the
NewAn object instance that obtains an address pointer in the stack, or the JVM cannot pass an implied parameter to a non-static method. The static method does not have this implicit argument and therefore does not require a new object, which can be called as long as the class file is ClassLoader load into the JVM's stack. Of course, at this point the static method is not accessible to object properties in the heap.
SummaryThis process: When a class file is ClassLoader load into the JVM, the method instruction is saved in the stack, where the heap has no data. Then the program technology starts executing the instruction, if it is a static method, executes the instruction code directly, of course, the instruction code is not accessible to the heap data area, if the non-static method, because the implied parameter has no value, will be an error. Therefore, before the non-static method executes, the new object is assigned data in the heap, and the address pointers in the stack are given to non-static methods, so that the program technology executes the instructions in turn, and the instruction code can now access the heap data area. Static and Dynamic properties: the previously mentioned object instances and the dynamic properties are all stored in the heap, and the heap must be accessed by the instruction (method of the Class) through the address pointers in the stack. It is therefore possible to infer that static properties are stored in the stack, unlike dynamic properties stored in the heap. Because all are in the stack, and the instructions and data in the stack are fixed-length, it is easy to calculate the offset, and therefore, regardless of the instruction (the method of the Class), you can access the static properties of the class. It is also because the static property is stored in the stack, so it has a global property. In the JVM, static properties are stored in the stack instruction memory area, and dynamic properties are stored in the heap data memory area. Stack stack (stack) is the memory instruction area of the JVM. Stack management is simple, push a certain length byte of data or instructions, stack pointer pressure stack corresponding byte displacement, pop a certain byte length data or instructions, stack pointer stack. The stack is fast, management is simple, and the data or instruction byte length of each operation is known. So Java basic data types, Java instruction code, constants are stored in the stack. The stack is also called the stack memory, is the Java program's runtime, is created when the thread is created, its
Life is the life that follows the thread
period, the thread end stack memory is also released, there is no garbage collection problem for the stack, as long as the thread ends, the stack is over. What about the data stored in the stack? And what is the format? The data in the stack is
stack frames (stack frame)The format exists, the stack frame is a memory block, is a data set, is a data set of method and run time data, when a method A is called to produce a stack frame F1, and is pressed into the stack, a method called the B method, so that the stack frame F2 is also pressed into the stack, after execution, Eject the F2 stack frame first, then pop up the F1 stack frame and follow the "
Advanced post-outPrinciples What data is there in the stack frame? There are 3 types of data stored in the stack frame:
Local Variables(Local Variables), including input parameters and output parameters, and variables within the method;
Stack Operation(Operand stack), record the operation of the stack, into the stack;
Stack frame Data(Frame Data), including class files, methods, and so on. It's boring, so let's draw a diagram to understand the Java stack, as shown in: Four, the heap heap is the memory data area of the JVM. Heap management is complex and allocates an indefinite amount of memory space each time, specifically to hold an instance of the object. Allocating a certain amount of memory in the heap to hold an object instance is actually just a matter of saving the property value of the object instance, the type of the property and the type tag of the object itself, and not the method of saving the object (by instruction, saved in the stack), in the heap Allocating a certain amount of memory in a saved object instance is similar to serializing an object. When an object instance is allocated in the heap, a 4-byte heap memory address is stored in the stack, which locates the object instance in the heap, making it easier to locate the object instance. The heap in Java is made up of
all threads are sharedArea of memory. 4.1 Generation JVM Heap can generally be divided into the following three parts:
PermPerm mainly save class,method,filed objects, this department of space generally will not overflow, unless a lot of classes loaded, but when it comes to hot deployment of the application server, sometimes encounter Java.lang.OutOfMemoryError: PermGen space error, the cause of this error is likely to be redeployed every time, but after redeployment, class is not unloaded, so that a large number of class objects are saved in the perm, in this case, Restarting the application server generally resolves the issue.
tenuredTenured the main preservation of the long life cycle of the object, usually some old objects, when some objects in young copy transfer a certain number of times, the object will be transferred to the tenured area, generally if the system with application level of cache, Objects in the cache are often transferred to this interval.
YoungThe young area is divided into three parts, the Eden area and two strictly identical survivor areas, of which the survivor interval, only one of which is used at a time, and the other one for garbage collection, when the young interval becomes full, minor The GC will move the surviving objects to an idle survivor interval, and depending on the JVM's strategy, the objects that survived the survivor will be moved to the tenured interval after several garbage collections. The 4.2 Sizing The Generations JVM provides the appropriate parameters to configure the memory size. As described above, the heap in the JVM is divided into 3 large intervals, while the JVM also provides some options to control the size of the young,tenured.
Total Heap-XMS: Specifies that the JVM initializes memory after initial startup-xmx: Specifies that the JVM heap the maximum memory, after the JVM is started, allocates the memory of the-XMX parameter size to the JVM, but not necessarily all, the JVM adjusts the memory that is actually used for the JVM based on the-XMS parameters-xmx- The XMS difference is the size of three virtual spaces.
Young Generation-xx:newratio=8 means that the ratio of tenured to young is 8:1, so eden+2*survivor=1/9 heap memory-xx:survivorratio=32 means Eden and a survivor ratio is 32:1, Such a survivor accounted for 1/34 of the young area. The-XMN parameter sets the size of the young generation
Perm Generation -xx:permsize=16m-xx:maxpermsize=64m thread stack -xx:xss=128k V, the PC Register program counter Register  JVM supports multiple threads running concurrently. Each JVM has its own program counter. At any point, each JVM thread executes the code of a single method, which is the current method of the thread. If the method is not native, the program counter register contains the address of the currently executing JVM directive, and if the method is native, the value of the program counter register is not defined. The JVM's program counter register is wide enough to hold a return address or native pointer. The method area object class data (class definition) is stored in the method area. In addition, constants, static variables, and JIT-compiled code are all in the method area. Because the data stored by the method area has an analogy with the heap, it is also called Non-heap. The method area can also be a contiguous area of memory, and can be set to a fixed size or extensible, as is the case with heaps. There is a very important area within the method area called the run-time Constant pool, or RCP. There is a Chang (Constant Pool Table) in the bytecode file that stores the literal and symbolic references produced by the compiler. Chang in each bytecode file are stored in the method area after the class is loaded. It is important to note that the new constants produced by the runtime can also be put into constant pools, such as constants produced by The Intern () method in the String class. 6.1 Chang (constant pool) constant pool refers to some of the data that is determined at compile time and is saved in the compiled. class file. In addition to the constant values (final) that contain the various basic types defined in the code (such as int, long, and so on) and object types (such as strings and arrays), there are also some symbolic references that appear as text, such as: Class and interface fully qualified name; The name and descriptor of the field; method and name and descriptor. The virtual machine must maintain a constant pool for each mounted type. A constant pool is an ordered set of constants used by that type, including direct constants (String,integer and floating point constants), and symbolic references to other types, fields, and methods. for string constants, itThe value is in the constant pool. The Chang in the JVM exists as a table in memory, and for string types there is a fixed-length constant_string_info table for storing literal string values, note that the table stores only literal string values and does not store symbol references. In this case, there should be a clearer understanding of where the string values in the constant pool should be stored. When the program executes, the constant pool is stored in the method area, not the heap. Vii. Java method Stackjava methods Stack and native method stack native methods stack seventh chapter content Source: http://blog.csdn.net/poechant/article/ details/7289093
Java method stack is also thread-private, each Java method stack is composed of a stack of frames, each stack frame is a method run time of the basic data structure, it stores the local variable table, the operand stack, dynamic link, method export and other information. When a thread calls a Java method, a stack frame is pushed into the corresponding Java method stack. When a thread returns from a Java method, the corresponding Java method stack pops up (POPs) a stack frame.
The details of this is the local variable table, which holds various basic data types and object references (object reference). The basic data types are Boolean, Byte, char, short, int, long, float, double. An object reference, which is essentially an address (or a "pointer"), is an address in the heap where the corresponding object can be found (note "found" for reasons explained below). There are two ways to find the corresponding Object in this address. One is that the address stores Pointer to object Instance data and Pointer to object Class data, and the other is that the address stores Object Instance data, which contains Pointer to Object Class Data. As shown in the two figure below.
In the first way, the Java method stack has Handler pool and Instance pool. Either way, object Class data is stored in the method area, and object Instance data is stored in the heap.
Figure 1 Handle mode
Figure 2 Direct mode
The native method stack is similar to the Java method stack and is not mentioned here.
Eight, the JVM operating principle examples above are pure theory, we give an example to illustrate the operation of the JVM principle, we write a simple class, the code is as follows: Java code
- Public class Jvmshowcase {
- Static class constants,
- Public final static String class_const = "I ' m a CONST";
- Private instance variables
- Private int instancevar=15;
- Public static void Main (string[] args) {
- Calling a static method
- Runstaticmethod ();
- Calling a non-static method
- Jvmshowcase showcase=New Jvmshowcase ();
- Showcase.runnonstaticmethod (100);
- }
- General static methods
- Public static String Runstaticmethod () {
- return class_const;
- }
- Non-static methods
- public int Runnonstaticmethod (int parameter) {
- int methodvar=This.instancevar * parameter;
- return Methodvar;
- }
- }
This class doesn't make any sense, don't guess what the class is doing, just write a more typical class, and then we'll look at how the JVM works, that is, after entering Java jvmshow, let's see how the JVM is handled:
Request free memory to the operating system. The JVM said to the operating system "give me 64M free memory", so the 1th step, the JVM to the operating system to request free memory for the system to find their own memory allocation table, find a segment of 64M memory write "Java Occupy" tab, and then the memory segment start address and terminate address to JVM,JVM ready to load class file.
allocates memory memory. 2nd step, the JVM allocates memory. When the JVM gets to 64M of memory, it begins to give the heap a memory, which is divided by the three different types of heap, and then allocates the stack memory as well.
file. 3rd step, examine and analyze the class file. Returns an error if an error is found.
loads the class. 4th step, load the class. Because the loader is not specified, the JVM uses the bootstrap loader by default, loading all classes under Rt.jar into the persistent storage area of the heap class, and Jvmshow is loaded into memory. Let's look at the stack memory, such as: Heap is empty, stack is empty, because no thread has been executed yet. Class Loader notifies execution enginer that the load is complete.
executes the engine execution method. 5th step, the execution engine executes the main method. The execution engine starts a thread, starts executing the main method, and before main executes, the method area looks like this: a Class_const constant was added to method region, which was generated the first time it was accessed. There are two objects in heap memory, object and showcase objects, as shown in: Why do you have object objects? Because it is the parent of Jvmshowcase, the JVM initializes the parent class first, and then initializes the subclass, with no control over how many of the parent classes are initialized. There are three stack frames in the stack memory, as shown in: At the same time, a program counter is created to point to the next statement to execute.
frees memory. 6th step, release the memory. At the end of the run, the JVM sends a message to the operating system saying, "I'm done with the memory."
IX. issues related to the JVM Q: What is the difference between heaps and stacks what is the difference between a heap and a stack? A heap is a storage object, but a temporary variable within an object is present in the stack memory, as in the example, the Methodvar is stored in the stack at run time. The stack is followed by threads, there is a stack on the thread, the heap follows the JVM, and there is a heap of memory on the JVM. Q: What exactly exists in the heap memory? What exactly exists in the heap memory? Answer: objects, including object variables and Object methods. Q: What is the difference between a class variable and an instance variable? What is the difference between a class variable and an instance variable? What's the difference? A: A static variable is a class variable, a non-static variable is an instance variable, and, to be blunt, a static variable is a variable that is statically modified, and a variable with no static modifier is an instance variable. Static variables exist in the method area, and instance variables exist in heap memory. Start at the beginning of the good, and you say this is different! Q: I've heard that class variables are initialized when the JVM starts, and it's different from what you're saying! Answer: Then you are hearsay, believe me, yes. Whether the method (function) is a value or a value or a pass-through address? Q: Is the Java method (function) a value or a pass? A: No, it is a pass-through address, specifically the value passed by the native data type, the address that the reference type passes. For raw data types, the JVM is handled by copying from the method area or Heap to the Stack, then running the methods in the frame, and then copying the variables back. Produce? Q: Why does it produce OutOfMemory? A: There is not enough free memory in the HEAP memory. This sentence to understand, not to say that the heap has no memory, is to say that the new application memory object is larger than the heap free memory, such as the heap is now free 1M, but the new application of memory needs 1.1M, so it will be reported OutOfMemory, the future of the object may request memory as long as 0.9M, So it was only once that OUTOFMEMORY,GC was normal, and it looked like an occasional incident, that's what happened. However, if the GC does not recycle at this time, it will produce a suspend condition, the system does not respond. Q: I do not have many objects, why do you still produce OutOfMemory? I don't have a lot of objects, do I? A: You inherit a lot of layers, the Heap produces the object is the first generation of the parent class, and then the child class, understand? What are the different errors? Q: What are some of the OutOfMemory errors? Answer: There are two kinds, namely "Outofmemoryerror:java Heap Size" and "OutOfMemoryError: Permgenspace ", both are memory overflow, heap size is said to apply not to new memory, this is very common, check the application or adjust heap memory size. "PermGen space" is because the permanent storage area is full, this is also very common, generally in the hot release environment, because each release of the application system does not restart, over time the permanent storage area of the dead object too many causes the new object can not request memory, general restart can be. Q: Why does it produce stackoverflowerror?? A: Because a thread consumes all of the Stack memory, it is usually caused by a recursive function. Can we exchange visits between them? Q: Can I see multiple JVMs on a single machine? Can I exchange visits between the JVMs? A: You can have multiple JVMs, as long as the machine withstands it. There is no exchange of visits between the JVMs, and you cannot access the B-JVM Heap memory in A-JVM, which is not possible. In previous versions of the JVM, the presence of A-JVM Crack affected B-JVM, and now the version is very rare. To use the garbage collection mechanism, the explicit Q: Why does Java use garbage collection instead of explicit memory management in C + +? The explicit memory management? A: In order to be simple, memory management is not every programmer can toss good. Q: Why didn't you describe the garbage collection mechanism in detail? Why don't you go into the garbage collection mechanism? A: garbage collection mechanism each JVM is different, JVM specification just define to automatically free memory, that is, it only defines the abstract method of garbage collection, how to implement each vendor is different, the algorithm varies, this thing really does not need to go deep. In the end, which areas are shared? What is private? Q: Exactly which areas in the JVM are shared? What is private? A: Heap and Method area are shared, others are private, Q: What is JIT, why didn't you say it? , why didn't you say? A: JIT refers to Just in time, some documents to the JIT as a part of the JVM to introduce, and some as part of the implementation of the engine to introduce, which is understandable. Java was born in an explanatory language, don't shush, even if compiled into a bytecode (byte code) is also for the JVM, it needs to be translated into the native code (native) to be executed by the machine, so the efficiency of the concerns raised. Sun in order to solve the problem put forward a new set of mechanisms, good, you want to compile into native code, no problem, I provide a tool on the JVM, the bytecode compiled into the native code, the next time you come to visit the native code directly, it became, inJIT was born, that's all. What other parts did you not mention? Q: What other parts of the JVM are you not mentioning? A: The JVM is an unusually complex thing, writing a brick book is not too much, there are a few things to explain: Chang (constant pool) in order to store the constants in the program,: and the area of the index number. For example, int i = 100, this 100 is placed in the constant pool. Security Manager: Provides Java runtime security controls to prevent malicious attacks such as specifying read files, write file permissions, network access, create processes, and so on, Class Loader to be loaded after security Manager certification passes class file. Method Index Table (Methods table), which records the address information for each method, and the address pointers in the Stack and Heap actually point to the Methods table address. Q: Why not suggest an explicit life System.GC () in the program?? A: Because the explicit declaration is to do a full scan of heap memory, that is, the complete GC, is the need to stop all activities (Stop TheWorld Collection), your application can withstand this? Q: What tuning parameters does the JVM have? A: Very much, to find their own, heap memory, stack memory size can be defined, even the heap memory of three parts, the new generation of the various scales can be adjusted.
"Go" Into the JVM series (i) Internal model and memory allocation