Java memory area and memory overflow exception

Source: Internet
Author: User

JVM Runtime Data area graph:

Program counter

program Counter Register ) is a small memory space that can be seen as the line number indicator of the bytecode that is being executed by the current thread. This memory area is the only area in the Java Virtual machine specification that does not stipulate any outofmemoryerror conditions .

Java Virtual Machine Stack

The virtual machine stack describes the memory model that the Java method executes: Each method creates a stack frame to store information such as local variable tables, operand stacks, dynamic links, method exits, and so on. a picture of a netizen below may be clearer:

The local variable table holds the various basic data types that are known during the pre-compilation period (Boolean , Byte , Char , Short , int , float , Long , double ), object reference (Reference types) and ReturnAddress type (point to the address of a bytecode directive). data of type long and double with a length of 2 takes up a local variable space (Slot), and the remaining data types occupy only 1 A. through the above statement (personal understanding), the local variable space is in slot (32-bit) as a spatial unit. Even if the byte type of the original byte size in the local variable table also occupies a slot (32 bits = 4 bytes).

in the Java in the virtual machine specification, Java The virtual machine stack Specifies two exceptions: if the thread requests a stack depth greater than the virtual machine allows, Stackoverflowerror will be thrown exception, if the virtual machine stack can be dynamically extended, if the extension cannot request enough memory, it will throw OutOfMemoryError exception. in other words, if the size of the line stacks is 1MB, if the current thread has a large number of recursion, then when the thread's stack frame sum exceeds 1MB,JVM it throws stackoverflowerror. In addition, the number of threads created requires allocating thread stack memory, but when the system has no memory to allocate, it throws outofmemoryerror. Say more is nonsense, practice is the truth, next try to make the above two kinds of virtual machine stack errors.

Test code:

public class Stacktest {public    static void recursion (int count) {        System.out.println ("count=" +count);        Recursion (++count);    }        public static void Main (string[] args) {        recursion (0);}    }

The server and JVM information is as follows:

Make the above code into a jar running in this environment:

[Email protected] javatest]$ Java-jar stacktest.jarcount=0count=1......count=8406count=8407count=8408exception in Thread "main" Java.lang.StackOverflowError at        sun.nio.cs.utf_8$encoder.encodeloop (utf_8.java:691)        at Java.nio.charset.CharsetEncoder.encode (charsetencoder.java:579) at        Sun.nio.cs.StreamEncoder.implWrite ( streamencoder.java:271) at        sun.nio.cs.StreamEncoder.write (streamencoder.java:125)        at Java.io.OutputStreamWriter.write (outputstreamwriter.java:207) at        Java.io.BufferedWriter.flushBuffer ( bufferedwriter.java:129) at        Java.io.PrintStream.write (printstream.java:526) at        Java.io.PrintStream.print (printstream.java:669)        At Java.io.PrintStream.println (printstream.java:806) at        stacktest.recursion (stacktest.java:5)        at Stacktest.recursion (Stacktest.java:6)

As can be seen from the above information, when the recursion method runs to count=8408, the line stacks has exceeded the JVM default threadstacksize size (1MB), then throws a Stackoverflowerror exception.

Next we try to consume as much system memory as possible by increasing the set thread stack size (threadstacksize) value, causing the OutOfMemoryError exception to be thrown when the thread stack memory is no longer allocated:

[Email protected] javatest]$ java-jar-xss2048m Stacktest.jar        Error occurred during initialization of VMJAVA.LANG.O Utofmemoryerror:unable to create new native thread at        java.lang.Thread.start0 (native Method)        at Java.lang.Thread.start (thread.java:714) at        java.lang.ref.reference.<clinit> (reference.java:187)

The JVM thread lock consumes the memory of the Java process, but does not consume the memory of the JVM, and the maximum number of threads opened by a process can be understood in the following formula:

number of threads = (the maximum amount of memory allocated by the process-JVM Memory- reserved Operating system memory)/ Thread Stack size

The maximum allocated memory size of the process is related to the operating system, because the total memory size of my virtual server is 2GB, so I try to allocate 2GB memory size by-XSS parameter to line stacks, let the virtual machine throw an exception.

Local method Stack

The local method stack (Native is very similar to the virtual machine stack, but the difference between them is that the virtual machine stack executes Java for the virtual machine method (that is, the bytecode) service, while the local method stack is the native used by the virtual machine method Service.

Java Heap

Java Heap is Java The largest chunk of data in memory managed by a virtual machine is created at the time the virtual machine is started and shared by all threads. The only purpose of this memory area is to hold object instances where almost all object instances allocate memory, such as object instances and arrays. But as other technologies mature (like JIT), object allocation slowly becomes less "absolute" on the heap. The Java Heap is also the main area of garbage collector management, and since the collector basically uses the Generational collection algorithm, the Java heap can be subdivided into the new generation and the old age. The current mainstream virtual machines are implemented in a scalable way (via-xmx and-xms control). A OutOfMemoryError exception is thrown if there is no memory in the heap to complete the instance assignment and the pair cannot be extended . continue on the Code manufacturing Memory overflow:

public class Heaptest {public    static void Main (string[] args) {        list<byte[]> bytelist = new Arraylist<by Te[]> ();        for (int i=0;i<10000;i++) {            bytelist.add (new byte[1024000]);            System.out.println ("count=" +i);}}    

Packaged for Heaptest.jar testing:

[Email protected] javatest]$ Java-jar Heaptest.jar count=0count=1......count=405count=406exception in thread "main" Java.lang.OutOfMemoryError:Java heap space at        Heaptest.main (heaptest.java:9)

By printing the information, the heap overflows when the program creates a NO. 406 byte array (1MB per array).

Method area

Method Area ) and Java Heap, an area of memory shared by each thread that stores data such as class information, constants, static variables, and code compiled by the instant compiler that have been loaded by the virtual machine. The method area is also called Non-heap(not a heap), and is intended to be distinguished from the Java heap, and can be set by-xx:maxpermsize memory size. from the JVM Runtime Zone memory model (the first picture in this article), the heap and the method area are two separate blocks of memory. But from the garbage collector's point of view, the design team of the hotspot virtual machine chooses to extend the GC collection to the method area, or use the permanent generation to implement the method area, so many people prefer to refer to the method area as a "permanent generation", as shown in:

The runtime Constant pool is a part of the method area that holds the various literal and symbolic references generated by the class file at compile time, because the class file, in addition to the description information such as the version, field, method, interface, etc. Another piece of information is a constant pool (Constant pool Table). This section is stored in the run-time pool of the class load backward into the method area. Running a constant pool at the same time is dynamic, not the memory of the const pool in the class file is pre-placed into the method area to run the frequent pool, and new constants may be put into the pool during run time, such as the Inter () method of the String class. Since the run-time constant pool is part of the method area, it is naturally constrained by the method area memory, which throws a OutOfMemoryError exception when the constant pool is no longer able to request memory. continue on the Code manufacturing Memory overflow:

public class Methodareatest {public        static void Main (string[] args) {        list<string> List = new arraylist< String> ();        int i = 0;        while (true) {            System.out.println (i);            List.add (("Methodareatest" +string.valueof (i++)). Intern ());}}    

Since the JDK1.8 hotspot virtual machine is removed from the permanent generation, the regression JDK1.6 test:

Packaged for Methodareatest.jar testing:

[Email protected]:~/javatest> java-jar methodareatest.jar12 ... 815311815312815313Exception in thread "main" Java.lang.OutOfMemoryError:PermGen space at        Java.lang.String.intern (Native Method) at        Methodareatest.main (methodareatest.java:11)

By printing the information you can see that the method area memory overflow (after all, the constant pool belongs to the method area) has occurred after intern 815,313 times.

To run a constant-rate pool:

The Runtime Constant Pool is part of the method area. Used to hold various literal and symbolic references generated by the compiler, which will be stored in the run-time pool of the method area after the class is loaded.

A OutOfMemoryError exception is thrown when a constant pool is no longer able to request memory.

Direct Memory:

Direct Memory is a channel-and buffer-based I/O approach introduced by JDK1.4, not part of the data area when the virtual machine is running, nor the memory area defined in the Java VM specification, but is also frequently used. Used in Java's NiO (New input/output, JDK1.4), it can use the native library to directly allocate out-of-heap memory and then manipulate it through a Directbytebuffer object stored in the Java heap as a reference to that memory. . The server administrator ignores the direct memory consequence that the sum of each memory region is greater than the physical memory limit, resulting in a OutOfMemoryError exception when dynamic scaling occurs.

Java memory area and memory overflow exception

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.