Understanding OutOfMemoryError Exceptions-Drill down into Java Virtual machine reading summary

Source: Internet
Author: User
Tags throwable

Exceptions in the JVM occurIn addition to the program counters in the Java Virtual Machine specification, there are several other run-time areas where OutOfMemoryError exceptions can occur. This chapter notes the code to verify the contents of each run-time zone described in the Java Virtual Machine specification, and, in the event of an actual memory overflow exception, can quickly determine which area of memory overflow, what code might cause memory overflow in these areas, depending on the information of the exception. And how to deal with these problems.
  1. Java Heap Overflow: the Java heap is used to store object instances as long as objects are created and guaranteedGC RootsThere is a reachable path between objects to avoid a garbage collection mechanism to purge objects, which results in a memory overflow exception when the number of objects reaches the maximum heap capacity limit.-xms Set heap minimum,-xmx set heap maximum,-xx:+heapdumponoutofmemoryerror settings dump the current memory heap dump snapshot when the virtual machine has an oom exception. where the heap minimum and maximum values are set identically, the heap is not extensible.
    /***-xms20m-xmx20m-xx:+heapdumponoutofmemoryerror*/ Public classHeapoom {Static classoomobject {Object obj=NewObject (); }      Public Static voidMain (string[] args) {List<OOMObject> list =NewArraylist<oomobject>();  while(true) {List.add (Newoomobject ()); }     }}
    to resolve the exception in this area, you can analyze it through a snapshot of the heap dump of the memory image analysis tool, with the emphasis on verifying that the memory is leaking (Leak) or memory overflow (Overflow). If it is a memory leak, see the relevant reference chain through the tool. If it is a memory overflow, you should check the heap parameters of the virtual machine, compare with the physical memory of the machine to confirm whether it can be adjusted, and check the code for the existence of some objects with too long life cycle and too long holding state.
  2. Virtual machine stack and local method stack Overflow: Java Virtual machine about virtual machine stack and local method stack describe two kinds of exceptions
    Stackoverflowerror: Thrown when the stack depth of a thread request is greater than the maximum allowed depth of the virtual machine
    OutOfMemoryError: Thrown when a virtual machine cannot request enough memory space on the scale stack
    the-xoss parameter sets the local method stack memory capacity, and the-XSS parameter sets the virtual machine stack memory capacity.
    /***-xss128k * use-XSS to reduce stack memory capacity. * Define a large number of local variables and increase the length of the local variable table in the method frame.*/ Public classjavavmstacksof {Private intStacklength = 1;  Public Static voidMain (string[] args) {javavmstacksof javavmstacksof=Newjavavmstacksof (); Try{javavmstacksof.test (); } Catch(Java.lang.StackOverflowError e) {System. out.println (javavmstacksof. stacklength); }     }      Public voidTest () {++stacklength;     Test (); }}
    Single-threaded, whether because the stack frame is too large, or the virtual machine stack capacity is too small, when the memory can not be allocated, the virtual machine throws a Stackoverflowerror exception.If a memory overflow exception can be generated by creating a thread, the exception is not related to whether the stack space is large enough, because in this case, the larger the memory allocated to the thread's stack, the more prone to memory overflow exceptions. cause: The stack's life cycle is the same as the thread, and the larger the stack capacity each thread allocates, the fewer threads can be created. In addition, the remaining memory calculation method in the virtual machine is calculated as follows: remaining memory = Operating system limits process memory-maximum heap capacity-maximum method area capacity. Program counters consume very little memory, can be ignored, if the virtual machine process itself is not calculated, the rest isVirtual Machine StackAndLocal Method StackIt's divided.Therefore, if a memory overflow caused by multithreading has been established, it is only possible to reduce the number of threads or replace a 64-bit virtual machine by reducing the maximum heap(I think it should also be possible to reduce the maximum method area)and reduce stack capacity in exchange for more threads.
  3. Run a constant pool overflow:The run-time allocation is within the method area and can limit the size of the method area through-xx:permsize and-xx:maxpermsize, thereby indirectly limiting the capacity of the constant pool. The experiment code failed on the JDK 1.7.0_72.
    /***-xx:permsize=10m-xx:maxpermsize=10m *@authorAdministrator **/ Public classRuntimeconstantpooloom { Public Static voidMain (string[] args) {List<String> list =NewArraylist<string>(); inti = 0;  while(true) {List.add (String. valueOf (i++). Intern ()); }     }}
    Run a constant pool overflow, followed by OutOfMemoryError after the prompt message is "PermGen space",Description The run-time-constant pool is part of the method area。
  4. Method Area overflow: Method area overflow is a common memory overflow exception,The size of the method area can be limited by-xx:permsize and-xx:maxpermsize, and in applications where a large number of classes are generated dynamically, special attention needs to be paid to the recycling of the class. Dynamically generated classes can use Cglib bytecode enhancement, dynamic JSP files, and OSGi-based applications. The following code is the use of cglib to make a memory overflow exception in the method area
    /***-xx:permsize=10m-xx:maxpermsize=10m*/ Public classJavamethodareaoom { Public Static voidMain (string[] args) { while(true) {Enhancer enhancer=Newenhancer (); Enhancer.setsuperclass (oomobject.class); Enhancer.setusecache (false);           Enhancer.create (); }     }     Static classoomobject {}}
  5. Native Direct Memory Overflow:Direct Memory (directmemory) capacity can be specified by-xx:maxdirectmemorysize if you do not specify a maxdirectmemorysize default value that is the same as the maximum value of the Java heap. The following code uses the unsafe feature to request the allocation of memory.
    /***-xmx20m-xx:maxdirectmemorysize=10m*/ Public classDirectmemoryoom {Private Static Final int_1MB = 1024*1024;  Public Static voidMain (string[] args)throwsIllegalArgumentException, illegalaccessexception {Field Unsafefield= Sun.misc.Unsafe.class. Getdeclaredfields () [0]; Unsafefield.setaccessible (true); Sun.misc.Unsafe Unsafe= (Sun.misc.Unsafe) unsafefield.get (NULL);  while(true) {unsafe.allocatememory (_1MB); }     }}

Method entry recommendations using JavaBean delivery

When the method parameters are often not easy to read and maintain, it is recommended to use a javabean to wrap the arguments in. On the other hand of this proposal, consider the following question

 Public classMybean {Private Final DoubleA; Private Final Doubleb;  PublicMybean (DoubleADoubleb) { This. A =A;  This. B =b; }     Public DoubleGeta () {returnA; }     Public DoubleGetb () {returnb; }}
 Public classStackoverflowtesta {Private Static intInvokemethodcount = 0;  Public Static voidmethod (Mybean mybean) {++Invokemethodcount;        System.out.println (Invokemethodcount); //Method (New Mybean (Mybean.geta (), MYBEAN.GETB ()));method (Mybean); }     Public Static voidMain (string[] args) {Try{method (NewMybean (1L, 2L)); } Catch(Throwable e) {System.out.println ("Number of Calls:" +invokemethodcount); }    }}
 Public classSTACKOVERFLOWTESTB {Private Static intInvokemethodcount = 0;  Public Static voidMethodLongALongb) {++Invokemethodcount;        System.out.println (Invokemethodcount);    Method (A, B); }     Public Static voidMain (string[] args) {Try{method (1L, 2L); } Catch(Throwable e) {System.out.println ("Number of Calls:" +invokemethodcount); }    }}

We all know that the Java Virtual machine stack has limited space and stackoverflowerror errors occur when there is infinite recursive code.
So, consider which recursion depth is deeper in the code above Stackoverflowtesta and Stackoverflowtestb? If the method parameter in Stackoverflowtestb becomes a two short type?

Understanding OutOfMemoryError Exceptions-Drill down into Java Virtual machine reading summary

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.