Learn JVM (i)--java memory area

Source: Internet
Author: User
Tags instance method

Objective

Make a small summary of the JVM learning process by learning more about the Java Virtual machine tutorials, as well as your own online query information.

This article begins with a description of the memory distribution area of Java, followed by memory allocation principles and memory monitoring tools. Again, this section focuses on garbage collection, which deals with garbage tagging algorithms and various garbage recovery algorithms, and then roughly describes the garbage collectors used on the market. After that, summarize the above principles and explain the relevant JVM tuning cases. The class loading process is then highlighted. The last chapter of the byte code part, byte code is relatively dull and particularly cumbersome content, it is best to do their own work with the study will be better, or view its rough, superficial understanding can also.

Java Memory Area

? Let's start with a simple Java code to create an object. Hot, like,

//运行时, jvm把TestObjectCreate的信息都放入方法区 public class TestObjectCreate {    //main方法本身放入方法区    public static void main(String[] args) {        Sample test1 = new Sample("测试1");        //test1是引用,所以放到栈区里,Sample是自定义对象应该放到堆里面        Sample test2 = new Sample("测试2");        test1.printName();        test2.printName();    }}//运行时, jvm把Sample的信息都放入方法区 class Sample {    //new Sample实例后,name引用放入栈区里,name对象放入堆里    private String name;    public Sample(String name) {        this.name = name;    }    public void printName() {        System.out.println(name);    }}

? The interaction diagram of stack, heap, and method area is as follows,

? To get to the point, Java's memory area is generally divided into two major areas: the thread exclusive zone and the thread share area.

? Thread Exclusive zone: Virtual machine stack, local method stack, program counter

? Thread Sharing: heap, method area

Thread Exclusive Zone

? As the name implies, the thread exclusive zone is the memory area that is unique to each thread during the running process. In this memory space, there is our usual knowledge of the stack , professional terminology called 虚拟机栈 , because there is another area called 本地方法栈 , and then in addition to the above two stacks, there is one 程序计数器 . The thread exclusive area is roughly divided into these three pieces of content.

Virtual Machine Stack

? The virtual machine stack is often mentioned in our daily development of the stack, there are actually several concepts:,,, 栈帧 局部变量表 操作数栈 动态连接 , 返回地址 .

Stack frame

? Stack frame is a data structure used to support virtual machines for method invocation and method execution, which is the stack element of the virtual machine stack in the data area when the virtual machine is running.

? The way we say it in the stack, refers to the stack frame. Each method from the start of the call to the completion of the process, corresponding to a stack frame in the virtual machine stack from the stack to the process. For the execution engine, in the active thread, only the stack frame at the top of the stack is valid, called the current stack frame, and the method associated with the stack frame is called the current method. All bytecode directives run by the execution engine operate on the current stack frame only.

? When a Java program is compiled into a class file, the size of the stack frame is determined, and the size of the stack frame does not change when the JVM is running .

? The stack frame stores information such as the local variable table of the method, the operand stack, the dynamic connection, and the method return address.

Local variable table

? The local variable table is a 重点 piece of comparison, because in the normal Java development process, the contact is still relatively straightforward, so the content of the local variable table needs to be remembered and understood. The local variable table contains not only the local variables in our method, but also the list of parameters that are saved into the local variable table, and the this pointer of the non-static method is also stored in the 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.

? What we normally call a new object, then opens up a space in the heap, then adds a reference to the heap in the stack, and a reference to the local variable table is added here.

? The system does not assign the initial value to the local variable (the instance variable and the class variable are given the initial value). That is, there is no preparation stage like a class variable .

? When a Java program is compiled into a class file, the capacity of the maximum local variable table that the method needs to allocate is determined in the Max_locals data item of the method's Code property.

? The capacity of the local variable table is the smallest unit in the variable slot (slot), wherea slot in a 32-bit virtual machine can hold a data type that is less than 32 bits (Boolean, Byte, char, short, int, float, Reference and ReturnAddress eight species).

? The reference type virtual machine specification does not explicitly describe its length, but in general, the virtual machine implementation should at least be able to find, directly or indirectly from this reference, the object type data in the starting address index and the method area of the objects in the Java heap.

? The returnaddress type is for bytecode instruction JSR, Jsr_w, and RET, which points to the address of a bytecode directive.

? for a 64-bit data type, the virtual opportunity allocates two contiguous slot spaces to the high-level in the previous way. the 64-bit data type explicitly specified in the Java language is similar to the practice of splitting a long and double data types into two 32-bit reads and writes in a long and double non-atomic contract with a long and double data type split storage. Read the Java memory model in contrast. However, because the local variable table is built on the thread's stack, the data is private, regardless of whether the read-write two consecutive slots are atomic operations, no data security issues are caused.

? The virtual machine uses the local variable table through index positioning, and the index value ranges from 0 to the maximum number of slots in the local variable table. if a variable of 32-bit data type, index n represents the use of the nth slot, if it is a variable of 64-bit data type (long, double), then the nth and n+1 two slots are used.

? a virtual machine is the process of passing a parameter value to a list of parameter variables using a local variable table, and if it is an instance method (not static), then the slot for the No. 0-bit index of the local variable table defaults to the reference used to pass the object instance to which the method belongs, and is accessed through this in the method.

? In order to save stack frame space as much as possible, the slots in the local variable table can be reused, the variables defined in the method body will not necessarily overwrite the entire method body, if the value of the current bytecode PC counter is beyond the scope of a variable, The slot that corresponds to this variable can be given to other variables for use.

? That is, the local variable table slot slot is reusable, when a variable has exceeded its scope, that is, the subsequent code is no longer used on it, then the JVM will reuse the variable slot slot for subsequent code to use the variable. Then there is another problem here, when the variable goes beyond its scope, the JVM retains its slot slot, and the variable is not actually recycled when the slot slot has not been reused , as in the following code

public class TestStackLocalVariableTable {    private static int _M = 1024 * 1024;    public static void main(String[] args) throws InterruptedException {        byte[] array = new byte[60 * _M];        System.gc();    }}

? The code is also very simple, that is, new a 60M byte array, and then call GC garbage collection, the results of the operation as shown below, in the full GC eventually did not go to reclaim the variable. There is no array reason to reclaim the memory, because at execution System.gc() time, the variable is still in scope array , and the virtual machine naturally does not dare to reclaim this part of the memory. Let's change the code.

? (PS1: How did the results in the console print out?) In fact, in the run time on the virtual machine to add parameters:-VERBOSE:GC, as shown below)

? (PS2: What does GC information look like in the console?) As a [GC (System.gc()) 64102K->62224K(125952K), 0.0170834 secs] result, the system has a GC operation, and then the result of the operation is from the original heap memory usage 64102k,gc into 62224K, only a little bit, that is actually recycled in fact other in the process of other space, And we define a 60M byte array is not recycled, and the result of the above is only the JVM Minor GC, Minor GC is only the heap memory of the Eden area memory, after the heap memory will be described in detail, it can be considered that the Minor GC is lightweight GC recovery, fast, And after the minor GC has not been successfully recycled, the JVM performs a full gc,full GC that scans the entire heap of memory gcroot to reclaim the garbage, and later on, it can be considered that the GC is a heavyweight garbage collection, slow, and the length of the recovery may be minor GC is several or 10 times times more than, to return to the point, that is, from the running results [Full GC (System.gc()) 62224K->62107K(125952K), 0.0230050 secs] , after the full GC has occurred, there is no collection of 60M byte array of memory)

? We modify the code above, as shown below, is actually going to be byte[] array = new byte[60 * _M] wrapped up in blocks of code.

public class TestStackLocalVariableTable {    private static int _M = 1024 * 1024;    public static void main(String[] args) throws InterruptedException {        {            byte[] array = new byte[60 * _M];        }        System.gc();    }}

? According to the original understanding, after the code block, the array object is no longer used, it should be called after the GC is recycled, but from the results below can be found that the array object is not recycled, because array the slot is reused, the JVM also retains arrayreference in the heap, the GC will not reclaim this part of the memory.

? Then modify the above code again, as below,

public class TestStackLocalVariableTable {    private static int _M = 1024 * 1024;    public static void main(String[] args) throws InterruptedException {        {            byte[] array = new byte[60 * _M];        }        int b = 0;        System.gc();    }}

? In fact, on the basis of the second code, add it, int b = 0 but from the result, the array object is recycled, because at this time, the operation of the local variable table, local variables are b reused array slot slot, full GC found array The object has not been referenced, it is array recycled.

? Although now know the principle, but in fact, the problem has not been solved, in the actual development, Asao the memory of the object is to be recycled, it is not possible to write a useless variable to manipulate the local variable table after the business code is written, what should be done?

? Therefore, when the orchestration is finished, the objects that will need to be reclaimed, preferably manually assigned NULL, help GC recycle.

public class TestStackLocalVariableTable {    private static int _M = 1024 * 1024;    public static void main(String[] args) throws InterruptedException {//        int a = 0;        {            byte[] array = new byte[60 * _M];            array = null; //手动赋值对象为null,array对象没有了引用,GC会将这个对象回收        }//        a = 1; //读取了局部变量表,但是没有复用array的Slot槽位,jvm还保留着array的引用,此时GC不会回收array对象//        int b = 0; //操作了局部变量表,复用了array的Slot槽位,array对象没有了引用,GC会将array对象回收        System.gc();    }}
Operand stacks

? In addition to the local variable table, each stand-alone stack frame contains a last-in, first-out (last-in-first-out) operand stack , or it can be called an expression stack. The operand stack and the local variable table have the big difference in the access way, the operand stack does not use the access index the way to carry on the data access, but through the standard stack and the stack operation to complete the data access. Each operand stack will have a clear stack depth for storing values, a 32bit value can be stored with a stack depth of one unit, while the stack depth of 2 units can hold a value of 64bit, of course, the size of the operand stack required to be fully determined during the compilation period, and saved in the Code property of the method.

? Any operation in the hotspot needs to be done through the stack and stack, so the implementation engine architecture of the hotspot is necessarily based on the stack architecture rather than the traditional register architecture. In a nutshell, the operand stack is a workspace of the JVM execution engine, and when a method is called, a new stack frame is created, but at this point the stack is empty, and only the method is executed during execution. There will be a variety of bytecode instructions to perform the stack and stack operations on the operand stack. For example, when a simple addition operation needs to be performed inside a method, the first step is to stack the two values from the operand stack that need to be performed, and then the results of the operation are put into the stack after the execution of the operation is completed.

? Here's a simple example to illustrate,

public class TestOperandStack {    public static void main(String[] args) {        add(1, 2);        int d = 2 + 2;    }    public static long add(int a, int b) {        long c = a + b;        return c;    }}

? The above paragraph is Java source code, the following is the result javap -verbose of printing according to the instructions (JAVAP is the JDK's own disassembly, you can see the Java compiler generated for us bytecode. It allows us to understand the internal work of many compilers against source code and bytecode. In the bytecode chapter will be more detailed explanation, there is no pre-knowledge can first look at the byte code chapter)

 public static void Main (java.lang.string[]); Descriptor: ([ljava/lang/string;) V flags:acc_public, Acc_static code:stack=2, locals=2, args_size=1 0  : iconst_1 1:iconst_2 2:invokestatic #2//Method add: (II) J 5:POP2 6:      Iconst_4 7:istore_1 8:return linenumbertable:line 6:0 line 7:6 line 8:8 Localvariabletable:start Length Slot Name Signature 0 9 0 args [ljava/lang/string            ;    8 1 1 D I public static long Add (int, int);         Descriptor: (II) J flags:acc_public, Acc_static code:stack=2, locals=4, args_size=2 0:iload_0         1:iload_1 2:iadd 3:i2l 4:lstore_2 5:lload_2 6:lreturn linenumbertable:       Line 11:0 line 12:5 localvariabletable:start Length Slot Name Signature 0   7 0 AI 0 7 1 B I 5 2 2 C J} 

? Read the result from the JAVAP, starting with code in Main, iconst_1 represents the int type constant 1 into the operand stack, iconst_2 represents the int type constant 2 into the operand stack, and then invokestatic calls the static method to invoke the Add method. Main stop, look at the Add code method, iload_0 means to remove the int variable into the operand stack from the local variable table, the mantissa 0 means that the first slot slot is a, and then Iload_ 1 is another one from the local variable table to take the int variable into the operand stack is B, and then the iadd instruction represents the two number of the top of the operand stack is taken out and added, will be a, a and a two number from the top of the operand stack, to add, i2l represents a type conversion instruction, int to the type of a long type Long) means long c = a + b; that this code converts the result int type that adds a and B to a long type, and then lstore_2 indicates that the long type variable, C, is added to the local variable table, and then lload_2 the variable that takes a long type from the local variable table is C, The lreturn indicates that a long type instruction is returned. This is the approximate flow of the operand stack for the sample code above.

? Here to add a knowledge point, return to the main method to pause the reading of the place, line 5th, POP2 represents the top of the operation of the stack 2 elements out of the stack, that is, the source code 1 and 2, the next instruction is Iconst_4, the corresponding source code we know, at this time the codes are gone int d = 2 + 2; , according to the previous interpretation, We understand that it should be two iconst_2 into the stack, and then do the iadd operation, but here the bytecode instruction is iconst_4, that is, the compiler is optimized, that is, compiler optimization, will be calculated during the compilation of the results are calculated first, Then, during the run, the value can be taken directly, one less step, because the Java principle is to compile, run multiple times, so the results that can be computed during compilation are processed by the compiler.

? In fact, the use of JAVAP to view the bytecode information or a very interesting thing, the suggestion has not played the classmate can write some code debugging debugging, see the results, you can see the principle of the previous invisible Touch things, debugging will have a different understanding, like "= =", equals,++i,i++ Wait a minute.

Dynamic connection

? each stack frame contains a reference to the owning method of the stack frame in the run-time pool, which is held to support dynamic connections during method invocation. There are a number of symbolic references in the constant pool of class files, and the method invocation directives in the bytecode are referenced as parameters to the symbol in the constant pool that points to the method. Some of these symbolic references are converted to direct references during the class load phase or the first use, which is called static parsing. The other part will be converted to a direct reference during each run, which is called dynamic connectivity.

return address

? Once a method has been executed, to return to the place where it was previously called, a method return address must be saved in the stack frame to restore the local variable table and the operand stack of the upper method, and to press the return value (if any) into the operand stack of the caller's stack frame, Adjust the value of the PC counter to point to an instruction that follows the method invocation instruction .

Local method Stack

? Local method, that is, native method, when looking at the JDK source code, you can often see, like object GetClass method, Hashcode method, etc. are native methods, these methods are not implemented in Java, the local method is essentially dependent on the implementation, The designers of virtual machine implementations are free to decide what mechanism to use to get Java programs to invoke local methods.

? When a thread calls a local method, it enters a completely new world that is no longer restricted by the virtual machine. The local method can access the runtime data area of the virtual machine through the local method interface, but more than that, it can do anything it wants to do.

? Any local method interface will use some kind of local method stack. When a thread calls a Java method, the virtual opportunity creates a new stack frame and presses it into the Java stack. However, when it calls the local method, the virtual machine keeps the Java stack intact, and no longer presses the new frame into the thread's Java stack, and the VM simply dynamically connects and invokes the specified local method directly.

If a virtual machine implements a local method interface that uses the C connection model, then its local method stack is the C stack. When a C program calls a C function, its stack operation is deterministic. The arguments passed to the function are pressed into the stack in a certain order, and its return value is passed back to the caller in a deterministic manner. Again, this is the behavior of the local method stack in the virtual machine implementation.

? It is likely that the local method interface needs to callback the Java method in the Java virtual machine, in which case the thread will save the state of the local method stack and go to another Java stack.

Depicts a scenario where a local method calls back another Java method in a virtual machine when a thread invokes a local method. This image shows a panorama of the threads running inside the Java Virtual machine. A thread may execute a Java method throughout its lifecycle, manipulate its Java stack, or it may jump between the Java stack and the local method stack without hindrance.

? The thread first calls two Java methods, and the second Java method calls a local method, which causes the virtual machine to use a local method stack. Suppose this is a C language stack in which there are two C functions, the first C function is called by the second Java method as a local method, and the C function calls the second C function. The second C function then callbacks a Java method (the third Java method) through the local method interface, and finally the Java method calls a Java method (which becomes the current method in the diagram).

? The local method stack is very similar to the virtual machine stack, except that the virtual machine performs the Java method service for the virtual machine, and the local method stack executes the local method service for the virtual machine.

Program counter

? The program counter is a small amount of memory space, and his role can be seen as the line number indicator of the byte code executed by the current thread. In the virtual machine concept model (only the conceptual model, the various virtual machines may be implemented in some more efficient way), the bytecode interpreter works by changing the value of this counter to select the next need to execute the bytecode instruction, branch, loop, jump, exception handling, Basic functions such as thread recovery need to rely on this counter to complete.

? Because the multithreading of a Java Virtual machine is implemented in a way that threads rotate and allocate processor execution time, at any given moment, a processor (a kernel for a multicore processor) executes only the instructions in one thread. Therefore, in order for the thread to switch back to the correct execution location, each thread needs to have a separate program counter, the counters between the threads do not affect each other, isolated storage, we call this kind of memory area is "Thread exclusive zone" Memory . (In fact, it is also very well understood that each thread in the execution of bytecode instructions, it must be read the line number of the respective instructions to execute, if it is a thread sharing, the instructions are not all messed up?)

? if the thread is executing a Java method, this counter records the address of the executing virtual machine bytecode instruction, which is empty (undefined) 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. (because this part of the space is managed by the full JVM itself, not the programmer, and the memory footprint is small)

1. Popular Explanations:

? For a running Java program, each of these threads has his own PC (program counter) register, which is created when the thread starts, the size of the PC register is a word length, so it can hold a local pointer, can also hold a returnaddress (returnaddress type is used by the Java Virtual machine's JSR, ret, and jsr_w directives. The value of the ReturnAddress type only wants the opcode of a virtual machine instruction. Unlike the native types of the numeric classes described earlier, the ReturnAddress type does not have a corresponding type in the Java language, nor can it change the value of the ReturnAddress type during the program's run. )。 When a thread executes a Java method, the contents of the PC register are always the "address" of the next executed instruction, where the "address" can be either a local pointer or an offset in the method bytecode relative to the method's start instruction. If the thread is executing a local method, the value of the PC register is "Undefined".

2. Local methods and Java methods:

? There are two methods in Java: Java methods and local methods. Java methods are written in the Java language, compiled into bytecode, stored in the class file. Local methods are written in other languages (such as c,c++, or language), and are compiled into processor-related machine code. Local methods are saved in the Dynamic Connection library, and the format is specific to each platform. Java methods are platform-independent, but not in local methods. When a running Java program calls the local method, the virtual machine loads the dynamic library containing the local method and calls the method.

Thread Sharing Area

? Thread sharing is the memory space that is shared by each thread during the run. Which is included with the 方法区 .

Heap

? The Java heap is a piece of memory that is shared by all threads and created when the virtual machine is started. The only purpose of this area of memory is to hold object instances where almost all of the object instances are allocated memory. This is described in the Java Virtual Machine specification as: All object instances and arrays are allocated on the heap, but with the development of the JIT compiler and the gradual maturity of the escape analysis technology, stack allocation, scalar replacement optimization technology will lead to some subtle changes occur, All objects are allocated on the heap and gradually become less "absolute".

? Java heap can be a physically discontinuous space, as long as logically continuous, mainstream virtual machines are implemented in an extensible manner. If there is no memory in the current pair to complete the creation of the object instance, and the memory extension cannot occur, the OutOfMemory exception is thrown.

? The Java heap is the primary area of garbage collector management, so it is also known as the GC heap. If from the perspective of memory recycling, because the collector is now basically used in the generation of the collection algorithm, so the Java heap can be subdivided into: the new generation and the old age, and more detailed there is Eden space, from Survivor space, to survivor space.

? In the generational collection algorithm, the heap design as shown, divided into the new generation and the old age, and in the new generation and then subdivide a roughly 80% space in the Eden area, and two pieces of each of the 10% Space Survivor area (the space ratio can be configured), why so points, in this chapter is not said, because the content too much , and it involves the knowledge of garbage collection, so this piece of content is put in the garbage collection section to talk about.

? Write a segment code to verify the next heap memory generation, as below,

public class TestHeap {    private static int _M = 1024 * 1024;    @Test    public void testParallel() {        byte[] array = new byte[2*_M];    }}

? The code is simple enough to create an array of 2M size, but to keep track of the heap memory and GC, you also need to add the following JVM parameters at runtime

-verbose:gc //设置跟踪gc-XX:+PrintGCDetails //打印详细的gc内容-Xms20M //设置堆内存最小内存为20M-Xmx20M //设置堆内存最大内存为20M-Xmn10M //设置新生代内存为10M

? The result of the operation is as follows, it can be seen that my native JVM default garbage collector (parallel) used by the generation of collection algorithm, heap memory for the generation of management

? From the above results, do not know if anyone found a problem, is that I set the new generation is 10M, the old age is 10M (heap memory 20m-Cenozoic 10M), but the above results, the new generation of free space is 9216K, the old age is 10240K, the old age is 10M Yes, But how is the new generation 9M, less 1M? This problem is related to the replication algorithm, in the replication algorithm, there is a memory area is used to replicate the migration objects used, not counted into the actual space available.

? In addition, the lowest boundary and the highest boundary refer to the beginning and ending positions of this memory space, such as the Cenozoic Boundary: (0x0000000100000000-0x00000000ff600000)/1024/1024=10m, then, what is the current boundary? is the memory boundary of the current available space, so that the words do not understand, and then do an experiment to see the results can be understood.

? Adjust the parameters of the JVM, the above -Xmx20M , instead, the -Xmx40M other parameters unchanged, and then rerun the above program, the results are as follows

? Just the program, we set the minimum heap size of the JVM to 20M, and the maximum heap size is 40M, but we found that the new generation of space has been fixed to 10M, and the old age of free space total is actually 10M, because the JVM in memory enough, Will go to maintain a minimum heap space , so, at this time the program occupies space on the Eden area with a little more than 6M, far less than 20M, so at this time the free space is still maintained in 20M, we can take the current boundary of the old age to reduce the minimum boundary, to calculate, ( 0x00000000fe200000-0x00000000fd800000)/1024/1024=10m, with the highest boundary minus the minimum boundary, (0x00000000ff600000-0x00000000fd800000)/1024/ 1024=30m, that is, the heap space does set the maximum memory to 40M, but at this point the minimum heap memory is maintained at 20M.

? A few additional configuration parameters related to the heap, as follows

-XX:+printGC //打印GC的简要信息-XX:+PrintGCTimeStamps //打印CG发生的时间戳-Xloggc:log/gc.log //指定GC log的位置,以文件输出,可以帮助开发人员分析问题-XX:+PrintHeapAtGC //每次一次GC后,都打印堆信息-Xmn //设置新生代大小-XX:NewRatio //新生代(eden+2*s)和老年代(不包含永久区)的比值,如-XX:NewRatio=4表示新生代:老年代=1:4,即年轻代占堆的1/5-XX:SurvivorRatio //设置两个Survivor区和eden的比,如-XX:SurvivorRatio=8表示两个Survivor:eden=2:8,即一个Survivor占年轻代的1/10-XX:+HeapDumpOnOutOfMemoryError //OOM时导出堆到文件-XX:+HeapDumpPath //导出OOM的路径-XX:OnOutOfMemoryError //在OOM时,执行一个脚本,如"-XX:OnOutOfMemoryError=D:/tools/jdk1.7_40/bin/printstack.bat %p"
Method area

? In the Java Virtual Machine specification, the method area is treated as a logical part of the heap, but in fact, the method area is not a heap (non-heap); In addition, in many people's blogs, the Java GC's generational collection mechanism is divided into 3 generations: The green age, the old age, the permanent generation, these authors defined the method area as " Permanent generation ", this is because, for the previous implementation of the Hotspot Java Virtual machine, the idea of generational collection is extended to the method area, and the method area is designed as a permanent generation. However, most virtual machines other than hotspot do not treat the method area as a permanent generation, and the hotspot itself also plans to cancel the permanent generation.

? A method area is a zone shared by each thread that stores the class information that has been loaded by the virtual machine (that is, information that needs to be loaded when the class is loaded, including information such as version, field, method, interface, and so on), final constants, static variables, code that the compiler compiles immediately, and so on.

The method area is not physically required to be contiguous, you can choose a fixed size or an extensible size, and the method area has one more limit than the heap: You can choose whether to perform garbage collection. Generally, garbage collection performed on the method area is rare, which is one of the reasons that the method area is known as a permanent generation (HotSpot), but this does not mean that there is no garbage collection on the method area at all, and that garbage collection on it is mainly for the memory reclamation of the constant pool and unloading of the loaded classes.

Garbage collection on the method area, the conditions are harsh and very difficult, the effect is not satisfactory, so generally do not do too much to consider, you can stay for further in-depth study later use.

The Outofmemoryerror:permgen space exception is defined on the method area and is thrown when there is insufficient memory.

The runtime Constant pool is a part of the method area that stores the literal constants, symbolic references, and direct references that are generated by the compilation period (the symbolic reference is that the encoding is the location of a variable, an interface by a string. The direct reference is the translated address according to the symbol reference, which will be translated in the class link phase); Run a constant pool in addition to storing compile-time constants, you can also store constants generated at runtime (such as The Intern () method of the String class, which acts as a constant pool maintained by string. If the character "ABC" that is called is already in the constant pool, the string address in the pool is returned, otherwise a new constant is added to the pool and the address is returned.

Direct Memory

? Direct memory is not part of the data area when the virtual machine is running, nor is it an area of memory defined in the Java VM specification. The NIO class was added to the jdk1.4, which introduced a channel-based I/O method that can be used to directly allocate out-of-heap memory using the native library. It is then manipulated by a Directbytebuffer object stored in the Java heap as a reference to this memory. This can significantly improve performance in some scenarios because it avoids copying data back and forth in the Java heap and in the native heap.

? Obviously, the allocation of native direct memory is not limited by the size of the Java heap, but, since it is memory, it will certainly be subject to the size of the native total memory (including RAM and swap or paging files) and the processor addressing space. When the server administrator configures the virtual machine parameters, the parameters such as-xmx are usually set according to the actual memory, but the direct memory is often ignored, so that the sum of each memory area is greater than the physical memory limit (including physical and operating system-level limitations). This causes a OutOfMemoryError exception to occur when dynamic scaling occurs.

Learn JVM (i)--java memory area

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.