JVM Memory Management

Source: Internet
Author: User

 

VM runtime data area

Various data regions are used during JVM Java program execution. These regions have their own purposes, Creation Time, and destruction time. According to the Java Virtual Machine specification (version 2) (hereinafter referred to as the VM spec), the JVM includes the following runtime data regions:

 

1. program counter (program counter register ):

 

Each Java thread has a program counter to save the instruction of the current method that the program executes. For non-native methods, this region records the address of the VM primitive being executed, if the natvie method is being executed, this region is null (undefined ). This memory region is the only region in the VM spec that does not specify any outofmemoryerror conditions.

 

2. Java Virtual Machine stack (javavirtual machine stacks)

Like program counters, the life cycle of the VM stack is also the same as that of the thread. The VM stack describes the Memory Model of Java method calls. Each method creates a frame when it is executed) stores local variable tables, Operation stacks, dynamic links, method portals, and other information. The call to each method is complete, which means that a frame is in the VM stack and is transferred to the output stack. Later, we will focus on the local variable table section in the VM stack.

Some people often distinguish Java memory from heap memory and stack memory. The actual region is far more complex than this viewpoint, this division only indicates that the memory area closely related to the variable definition is the two. The "stack" is described later, and the "stack" refers to the local variable table of each frame in the VM stack. The local variable table stores various scalar types (Boolean, byte, Char, short, Int, float, long, and double) and object references (not the object itself, is just a reference pointer), method return address, etc. Long and double occupy two local variable spaces (32bit), and the other one. The local variable table is allocated when you enter the method. when you enter a method, it is completely determined how many local variables need to be allocated in the frame, during method running, the size of the local variable table is not changed.

In the VM spec, this region is set to 2: If the stack depth requested by the thread is greater than the depth allowed by the virtual machine, an stackoverflowerror exception will be thrown; if the VM stack can be dynamically expanded (a VM stack with a fixed length is allowed in the VM spec), an outofmemoryerror exception is thrown when the memory cannot be applied for during expansion.

3. native method stacks)

The role of the local method stack is similar to that of the VM stack, except that the VM Stack runs the VM primitive service, and the local method stack serves the native method used by the VM. The language, method, and structure of its implementation are not mandatory. Even some virtual machines (such as the sunhotspot Virtual Machine) directly combine the local method stack and the VM stack into one. Like the VM stack, stackoverflowerror and outofmemoryerror are thrown in this region.

4. Java heap)

For most applications, Java heap is the largest memory managed by virtual machines. Java heap is shared by all threads and is created when the VM is started. The only purpose of Java heap is to store object instances. Most object instances are allocated here. This is described in vmspec: all instances and arrays are allocated on the stack (Original: the heap is the runtime data area from which memory for all classinstances and arrays is allocated ), however, after the emergence of escape analysis and scalar replacement optimization technology, the description of the VM spec is not so accurate.

In the Java heap, there are more detailed divisions: the new generation and the old generation, and a little more detailed: Eden, from kernel vor, to kernel vor, and even more fine-grained local thread allocation buffer (tlab, no matter how the Java heap is divided, the objective is to better recycle the memory or allocate the memory faster. In this chapter, we will only discuss the role of the memory area, for details about the above regions in the Java heap, see Chapter 2 JVM memory management: Deep Garbage Collector and memory allocation policies.

According to the requirements of the VM spec, the Java heap can be in physically discontinuous memory space, which is logically sequential, just like our disk space. You can choose to implement a fixed or scalable Virtual Machine. However, all current commercial virtual machines are implemented according to scalability (controlled by-xmx and-XMS ). If memory cannot be allocated in the heap and the heap cannot be expanded, an outofmemoryerror error will be thrown.

5. Method Area)

The "Method Area" may not have many people who know it. If it is called "permanentgeneration", there may be more fans. It also has an alias called non-heap (non-heap), but on the VM spec, the method area is a logical part of the heap (original: the method area is logically part of the heap). The problem of this name is easy to misunderstand and we will not be confused here.

The method area stores the structure information of each class, including the constant pool, field description, and method description. The VM Space Description imposes very loose restrictions on this region. In addition to the Java heap and does not require continuous memory, you can also choose a fixed size or scalability, or even choose not to implement garbage collection. Relatively speaking, the garbage collection behavior rarely occurs in this region, however, it is not as described that GC will not occur on permanent generation (at least for mainstream commercial JVM implementations ), GC is mainly used to recycle the constant pool and unload the class. Although the "score" of the collection is generally unsatisfactory, especially when the class is detached, the conditions are quite harsh.

6. runtime constant pool)

In addition to class version, field, method, interface, and other descriptions, the class file also contains a constant table (constant_pool table) used to store known constants during the compilation period, this part of content will be stored in the Method Area (permanent generation) after the class is loaded. However, the Java language does not require constants to enter the constant table content of the class in the compilation period before entering the constant pool of the method area, you can also add new content to the constant pool (the most typical string. intern () method ).

The runtime constant pool is part of the method area and is naturally restricted by the method Area Memory. When the constant Pool cannot be applied to the memory, an outofmemoryerror exception is thrown.

 

7. Direct Memory)

Direct Memory is not part of the data zone of the VM runtime. It is the local memory instead of the zone directly managed by the VM. However, this part of memory also causes an outofmemoryerror exception, so we will describe it here.

The NiO class was added to jdk1.4, introducing an I/O Method Based on channels and buffers. It can be directly allocated to the local memory through the native function library on the local machine, then, use a directbytebuffer object stored in the Java heap as a reference to the memory. This can significantly improve performance in some scenarios, because it avoids copying data back and forth between the Java pair and the local heap.

Obviously, the direct memory allocation on the local machine is not limited by the Java heap size, but the memory must still be limited by the physical memory (including the swap area or Windows virtual memory) on the local machine, when a server administrator configures JVM parameters, the server administrator sets parameters such as-xmx based on the actual memory, but often ignores the Direct Memory, this causes an outofmemoryerror to occur when dynamic expansion occurs because the total amount of each memory area exceeds the physical memory limit (including physical and operating system-level restrictions.

 

Actual outofmemoryerror

In the above area, in addition to the program counter, other cases described in the VM spec that generate the outofmemoryerror (hereinafter referred to as OOM), we will simulate it in practice, through a few simple pieces of code, cause OOM exceptions in the corresponding region to deepen understanding, and introduce some memory-related virtual machine parameters. The code below is based on the implementation of Sun hotspot virtual machine version 1.6. For different versions of virtual machines in different companies, the parameters and program running results may be different.

 

Java heap

 

Java heap stores object instances. Therefore, as long as an object is continuously created and there is an reachable path between the GC roots and the object, an OOM exception occurs. In the test, the size of the Java heap is limited to 20 mb and cannot be extended. The parameter-XX: + heapdumponoutofmemoryerror is used to let the VM dump out the memory image in case of an OOM exception for analysis. (For details about dump Image File analysis, see Chapter 3 JVM memory management: Deep JVM Memory exception analysis and tuning.)

Listing 1: Java heap OOM Test

/**

* VM ARGs:-xms20m-xmx20m-XX: + heapdumponoutofmemoryerror

* @ Author zzm

*/

Public class heapoom {

 

Static class oomobject {

}

 

Public static void main (string [] ARGs ){

List <oomobject> List = new arraylist <oomobject> ();

 

While (true ){

List. Add (New oomobject ());

}

}

}

 

Running result:

Java. Lang. outofmemoryerror: Java heap Space

Dumping heap to java_pid3404.hprof...

Heap dump file created [22045981 bytes in 0.663 secs]

 

 

VM stack and local method Stack

 

The hot spot virtual machine does not distinguish between the VM stack and the local method stack. Therefore, the-xoss parameter is actually invalid, and the stack capacity is set only by the-XSS parameter. The VM stack and local method stack have two types of exceptions described in the vm spec: stackoverflowerror and outofmemoryerror. When the stack space cannot be further allocated, whether the memory is too small or the stack is too large is actually two descriptions of the same thing in a sense. In my experiment, for single-threaded applications, the following three methods cannot generate OOM for virtual machines. All the results are sof exceptions.

 

1. Use the-XSS parameter to reduce the stack memory capacity. Result: The stack depth decreases accordingly when an sof exception is thrown.

2. Define a large number of local variables and increase the frame length of the method. Result: The stack depth decreases accordingly when an sof exception is thrown.

3. Create several complex objects that define many local variables, enable escape analysis and scalar replacement options, and allow the JIT compiler to allocate objects in the stack after they are split. Result: The actual effect is the same as that of the second vertex.

 

Listing 2: VM stack and local method stack OOM test (only used as a 1st-point test program)

/**

* VM ARGs:-xss128k

* @ Author zzm

*/

Public class javavmstacksof {

 

Private int stacklength = 1;

 

Public void stackleak (){

Stacklength ++;

Stackleak ();

}

 

Public static void main (string [] ARGs) throws throwable {

Javavmstacksof OOM = new javavmstacksof ();

Try {

Oom. stackleak ();

} Catch (throwable e ){

System. Out. println ("Stack length:" + oom. stacklength );

Throw E;

}

}

}

 

Running result:

Stack length: 2402

Exception in thread "Main" Java. Lang. stackoverflowerror

At org. fenixsoft. oom. javavmstacksof. stackleak (javavmstacksof. Java: 20)

At org. fenixsoft. oom. javavmstacksof. stackleak (javavmstacksof. Java: 21)

At org. fenixsoft. oom. javavmstacksof. stackleak (javavmstacksof. Java: 21)

 

If a thread is continuously established in a multi-threaded environment, an OOM exception can be generated. However, basically, this exception is not directly related to the insufficient VM stack space, even the more memory allocated to the VM stack of each thread, the more likely the OOM exception will be generated.

 

The reason is actually quite understandable. The memory allocated to each process by the operating system is limited. For example, the 32-bit Windows system is limited to 2 GB, java heap and method area size JVM has a parameter that can limit the maximum value, the remaining memory is 2 GB (Operating System Limit)-xmx (maximum heap)-maxpermsize (Maximum Method Area ), the program counter consumes a small amount of memory and can be ignored. If the memory consumed by the virtual machine process itself is not calculated, the remaining memory is allocated to the VM stack of each thread and the local method stack, the more memory is allocated to the VM stack in each thread, the more likely it is to exhaust the remaining memory.

 

Listing 3: OOM exceptions caused by thread Creation

/**

* VM ARGs:-xss2m (larger at this time)

* @ Author zzm

*/

Public class javavmstackoom {

 

Private void dontstop (){

While (true ){

}

}

 

Public void stackleakbythread (){

While (true ){

Thread thread = new thread (New runnable (){

@ Override

Public void run (){

Dontstop ();

}

});

Thread. Start ();

}

}

 

Public static void main (string [] ARGs) throws throwable {

Javavmstackoom OOM = new javavmstackoom ();

Oom. stackleakbythread ();

}

}

 

Note: If you want to run the above Code, remember to save the current work on the disk. The above code may cause a high risk of freezing the operating system.

 

Running result:

Exception in thread "Main" Java. Lang. outofmemoryerror: Unable to create new Native thread

Runtime constant pool

 

To add content to the constant pool, use the native method string. Intern. Since the constant pool is allocated in the method area, we only need to use-XX: permsize and-XX: maxpermsize to limit the size of the constant pool. The implementation code is as follows:

 

Listing 4: OOM exceptions caused by the running frequent pool

/**

* VM ARGs:-XX: permsize = 10 m-XX: maxpermsize = 10 m

* @ Author zzm

*/

Public class runtimeconstantpooloom {

 

Public static void main (string [] ARGs ){

// Use list to keep constant pool reference and suppress full GC to reclaim constant pool behavior

List <string> List = new arraylist <string> ();

// The permsize of 10 m is sufficient to generate OOM in the Integer Range.

Int I = 0;

While (true ){

List. Add (string. valueof (I ++). Intern ());

}

}

}

 

Running result:

Exception in thread "Main" Java. Lang. outofmemoryerror: permgen Space

At java. Lang. String. Intern (native method)

At org. fenixsoft. oom. runtimeconstantpooloom. Main (runtimeconstantpooloom. Java: 18)

 

 

Method Area

 

As mentioned above, the method area is used to store class-related information. Therefore, in this area, we use cglib to directly operate on bytecode to dynamically generate a large number of classes. It is worth noting that, in this example, the simulated scenario is often used in actual applications: Currently, many mainstream frameworks, such as spring and hibernate, are used to enhance the class, cglib and other bytecode technologies are used. When more classes are enhanced, a larger method area is required to ensure that dynamically generated classes can be loaded into the memory.

 

Listing 5: Using cglib to cause OOM exceptions in the Method Area

/**

* VM ARGs:-XX: permsize = 10 m-XX: maxpermsize = 10 m

* @ Author zzm

*/

Public class javamethodareaoom {

 

Public static void main (string [] ARGs ){

While (true ){

Enhancer = new enhancer ();

Enhancer. setsuperclass (oomobject. Class );

Enhancer. setusecache (false );

Enhancer. setcallback (New methodinterceptor (){

Public object intercept (Object OBJ, method, object [] ARGs, methodproxy proxy) throws throwable {

Return proxy. invokesuper (OBJ, argS );

}

});

Enhancer. Create ();

}

}

 

Static class oomobject {

 

}

}

 

Running result:

Caused by: Java. Lang. outofmemoryerror: permgen Space

At java. Lang. classloader. defineclass1 (native method)

At java. Lang. classloader. defineclasscond (classloader. Java: 632)

At java. Lang. classloader. defineclass (classloader. Java: 616)

... 8 more

 

Local Direct Memory

 

The directmemory capacity can be specified through-XX: maxdirectmemorysize. If this parameter is not specified, it is the same as the Java heap (-xmx) by default. The following code goes beyond directbytebuffer, the getunsafe () method of the unsafe class directly obtains the unsafe instance for memory allocation (the unsafe class's getunsafe () method limits that only the boot class loader will return the instance, that is, basically only RT. classes in jar can be used only), because directbytebuffer will also throw an OOM exception, but when an exception is thrown, there is no real request for memory allocation from the operating system, instead, it is learned through calculation that unallocation will throw. The true method for applying for allocation is unsafe. allocatememory ().

 

/**

* VM ARGs:-xmx20m-XX: maxdirectmemorysize = 10 m

* @ Author zzm

*/

Public class directmemoryoom {

 

Private Static final int _ 1 MB = 1024*1024;

 

Public static void main (string [] ARGs) throws exception {

Field unsafefield = unsafe. Class. getdeclaredfields () [0];

Unsafefield. setaccessible (true );

Unsafe unsafe = (unsafe) unsafefield. Get (null );

While (true ){

Unsafe. allocatememory (_ 1 MB );

}

}

}

 

Running result:

Exception in thread "Main" Java. Lang. outofmemoryerror

At sun. Misc. Unsafe. allocatememory (native method)

At org. fenixsoft. oom. directmemoryoom. Main (directmemoryoom. Java: 20)

 

 

Reprinted from http://www.iteye.com/topic/802573

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.