Java Virtual machine--java memory area and memory overflow

Source: Internet
Author: User

Memory Area

The Java Virtual machine divides the memory he manages into several different data regions during the execution of a Java program. The Java Virtual Machine specification divides the memory managed by the JVM into the following runtime data areas: program counters, Java Virtual machine stacks, local method Stacks, Java heaps, method areas . The data types stored in each data area are described in detail below.

(Image from: http://blog.csdn.net/ns_code/article/details/17565503)

Program counter (Counter Register)

A smaller memory space, which is the line number indicator of the byte code executed by the current thread, and the bytecode interpreter works by changing the value of the counter to select the next byte-code instruction to be executed, and the basic functions such as branching, jumping, and looping are all dependent on it for implementation. each thread has a separate program counter, and the counters between the threads do not affect each other, so the zone is thread-private.

When a thread executes a Java method, the counter records the address of the executing virtual machine bytecode instruction, and when the thread executes the native method (called the local operating system method), the value of the counter is empty. In addition, the memory area is the only area in the Java Virtual Machine specification that specifies any oom (memory overflow: outofmemoryerror) condition.

java VM Stack (Java Virtual machine Stacks)

The zone is also thread-private, and its life cycle is the same as the thread. The virtual machine stack describes the memory model that is executed by the Java method: Each time a method is executed, a stack frame is created, which is the data structure used to support the continuation of the virtual machine for method invocation and method execution. 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, and all bytecode instructions run by the execution engine operate on the current stack frame only. stack frames are used to store local variable tables, operand stacks, dynamic links, method return addresses, and some additional additional information. When compiling program code, the number of local variable tables required in the stack frame, the number of deep operand stacks are fully determined, and the code attribute of the method table is written. therefore, how much memory a stack frame needs to allocate is not affected by the program run-time variable data, but only by the specific virtual machine implementation.

In the Java Virtual Machine specification, two exceptions are specified for this area:

1. A Stackoverflowerror exception is thrown if the thread requests a stack depth that is greater than the depth allowed by the virtual machine.

2. If the virtual machine cannot request enough memory space in the dynamic expansion stack, the OutOfMemoryError exception is thrown.

one thing to note here is that, in multithreaded situations, the larger the memory allocated to each thread's stack, the more prone to memory overflow exceptions. the operating system allocates a limited amount of memory per process, the virtual machine provides parameters to control the Java heap and the method area of the two parts of the maximum memory, ignoring the program counter consumption of memory (very small), and the process itself consumes memory, the rest of the memory is given to the virtual machine stack and the local method stack, The larger the stack capacity each thread allocates, the less the number of threads that can be established is natural. Therefore, if a memory overflow is caused by an excessive number of threads, it can only be exchanged for more threads by reducing the maximum heap and the stack capacity of each thread, in the case of fewer threads. When Oom is created due to an excessive thread creation, an error occurs: Java.lang.OutOfMemoryError, unable to create new native thread.

Local methods Stack (Native method Stacks)

This area is very similar to the virtual machine stack, except that the virtual machine stack executes Java method services for the virtual machine, while the local method stack is the local operating system (Native) method service that is used. As with the virtual machine stack, the local method stack area throws Stackoverflowerror and OutOfMemoryError exceptions.

Java Heap (Java heaps)

Java Heap is the largest piece of memory managed by a Java virtual machine, which is a chunk of memory shared by all threads, with almost all object instances and arrays allocating memory in this category. Java Heap is the main area of garbage collector management, so it is often referred to as the "GC heap".

According to the Java Virtual Machine specification, the Java heap can be in a physically discontinuous memory space, as long as it is logically contiguous. A OutOfMemoryError exception is thrown when there is no memory to allocate in the heap and the heap cannot be expanded.

Note: as the development of the JIT compiler and the escape technique matures, all objects are allocated on the heap and gradually become less absolute, and the thread-shared Java heap may also divide the outgoing private allocation buffer (TLAB).

Method Area

The method area is also an area of memory shared by each thread that stores data such as class information, constants, static variables, and code compiled by the immediate compiler that have been loaded by the virtual machine. the Java Virtual Machine specification describes the method area as a logical part of the Java heap, and it does not require contiguous memory like the Java heap, can be either fixed size or extensible, and the virtual machine specification allows the zone to choose not to implement garbage collection. Garbage collection behavior is relatively rare in this area. However, the recovery of this part of the area is necessary, if this part of the area is never recycled, then the type can not be unloaded, we can not load more classes, the hotspot of the region has garbage collection.

According to the Java Virtual Machine specification, a OutOfMemoryError exception is thrown when the method area does not meet the memory allocation requirements.

Direct Memory

Direct memory is not part of the data area when the virtual machine is running, nor is it a memory area defined in the Java VM Specification, which is allocated directly from the operating system and therefore is not limited by the Java heap size, but is subject to the size of the total memory of the machine and the processor addressing space. Therefore it can also cause outofmemoryerror anomalies to appear. In JDK1.4, a new NIO mechanism is introduced, which is a new I/O method based on channel and buffer, which can allocate direct memory directly from the operating system, that is, allocating memory outside the heap, which can improve performance in some scenarios because it avoids replicating data back and forth in the Java heap and the native heap.

When using more direct memory than allowed by the virtual machine, virtual machines throw a OutOfMemoryError exception, a memory overflow caused by directmemory, an obvious feature of which is that there is no visible exception in the heap dump file. In general, if you find that the dump file is very small after the oom, then you should consider whether this memory has been overrun.

Memory Overflow

Java Heap Memory Overflow

public class Heapoom {static class Oomobject {}public static void main (string[] args) {list<oomobject> List = new Ar Raylist<oomobject> (); while (true) {List.add (New Oomobject ());}}}

  When running the above code, you can increase the run parameter-xms20m-xmx20m, which restricts the Java heap size to 20M and is not extensible. The results of the operation are as follows:

Exception in thread ' main ' Java.lang.OutOfMemoryError:Java heap spaceat Java.util.Arrays.copyOf (Arrays.java : 2245) at Java.util.Arrays.copyOf (arrays.java:2219) at Java.util.ArrayList.grow (arraylist.java:242) at Java.util.ArrayList.ensureExplicitCapacity (arraylist.java:216) at Java.util.ArrayList.ensureCapacityInternal ( arraylist.java:208) at Java.util.ArrayList.add (arraylist.java:440) at Heapoom.main (heapoom.java:17)

You can see that the heap memory overflow, in addition to the error Java.lang.OutOfMemoryError , will also follow the further hint Java heap space.

Virtual machine stack and local method stack Overflow

To make the VM stack memory overflow, we can use recursive invocation: Because each method call needs to press the call information into the stack, when the stack size is fixed, the excessively deep recursion pushes the stack into excess information, resulting in stackoverflowerror:

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;}}}

  Run the above code and the output is as follows:

Stack length:10828Exception in thread "main" Java.lang.StackOverflowErrorat Javavmstacksof.stackleak ( JAVAVMSTACKSOF.JAVA:10) at Javavmstacksof.stackleak (javavmstacksof.java:11) at Javavmstacksof.stackleak ( JAVAVMSTACKSOF.JAVA:11)

As you can see, running the above code on my computer, the maximum supported stack depth is 10828 layers, when there is a stack overflow, will error java.lang.StackOverflowError.

Method Area Overflow

The method area is used to store class related information, such as class name, access modifier, field description, and so on, the basic idea for testing this area is that the runtime uses Cglib to generate a large number of classes to populate the method area until it overflows:

public class Javamethodareaoom {static class Oomobject {} public static void Main (STR Ing[] args) {while (true) {Enhancer enhancer = new Enhancer ()                                    ;                                    Enhancer.setsuperclass (Oomobject. Class);                                    Enhancer.setusecache (FALSE);                                                 Enhancer.setcallback (New Methodinterceptor () {@Override                                                                        public object intercept (object obj, Method method, object[] args,                                                             Methodproxy proxy) throws Throwable {                                                return Proxy.invokesuper (obj, args);                                    }                                    });          Enhancer.create ();              }            }} 

Add virtual machine parameters at runtime:-xx:permsize=10m-xx:maxpermsize=10m, limit the permanent generation size to 10M, and the last error is java.lang.OutOfMemoryError:PermGen space. The error message clearly indicates that the overflow area is a permanent generation.

Summarize

This article mainly explains which blocks of memory the Java Virtual machine is divided into, and whether these memory areas will be memory overflow, if there is a memory overflow error in these areas. Understanding this knowledge, later encountered memory overflow error, we can locate the specific memory area, and then specific problems, specific analysis.

Reference

    • http://blog.csdn.net/ns_code/article/details/17565503
    • "In-depth understanding of Java virtual machines"

Java Virtual machine--java memory area and memory overflow

Related Article

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.