Java Memory Overflow Example

Source: Internet
Author: User
Tags throwable

According to the structure of Java memory, memory overflow occurs in heap, stack, method area, direct memory .

First, heap overflow

Heap overflow is caused by too many objects, see Code:

/** * java heap overflow * VM args:-xms20m-xmx20m-xx:+heapdumponoutofmemoryerror * @author*/ Public classHeapoom {Static classOomobject {} Public Static voidMain (string[] args) {List<OOMObject> list =NewArraylist<oomobject>();  while(true) {List.add (Newoomobject ()); /*System.out.println ("Total (k):" +runtime.getruntime (). TotalMemory ()/1024+ "Freememory (k):" +runtime.                    GetRuntime (). Freememory ()/1024+ "MaxMemory (k):" +runtime.getruntime (). MaxMemory ()/1024+ "Availableprocessors:" +runtime.getruntime (). Availableprocessors ());*/        }    }}/** * Java.lang.OutOfMemoryError:Java heap spacedumping heap to java_pid1820.hprof ... Heap dump file created [24787111 bytes in 0.346 secs]exception in thread "main" Java.lang.OutOfMemoryError:Java Heap Spac E at Java.util.Arrays.copyOf (arrays.java:2760) at Java.util.Arrays.copyOf (arrays.java:2734) at Java.util.ArrayLis T.ensurecapacity (arraylist.java:167) at Java.util.ArrayList.add (arraylist.java:351) at Baby.oom.HeapOOM.main ( HEAPOOM.JAVA:19) * **/

Second, Stack Overflow

According to the Java Virtual Machine Specification Description: If the thread requests a stack depth that is greater than the maximum allowed depth for the virtual machine, the Stackoverflowerror will be thrown

If the virtual machine cannot request enough memory space on the scale stack, OutOfMemoryError will be thrown.

The experiment shows that the virtual machine throws the Stackoverflowerror when the memory cannot be allocated, either because the stack frame is too large or the virtual machine stack capacity is too small in a single thread.

A memory overflow overflow can be generated by constantly creating new threads. The larger the memory allocated for each thread's stack, the more likely it is to produce a memory overflow exception. If a memory overflow caused by multithreading has been established, it can only be exchanged for more threads by reducing the maximum heap and reducing the stack capacity, without reducing the number of threads or replacing 64-bit virtual machines.

Assuming that the 32-bit Windows system virtual machine is set to a maximum of 2G, the virtual machine provides parameters to control the Java heap and the method area of the two parts of the maximum value, the remaining memory is 2g-xmx-maxpermsize, if the virtual machine itself process memory size does not count, The saved memory has a virtual machine and a local method stack. The larger the stack capacity each thread allocates, the less the number of threads that can be established is natural.

/** Stack exception * If the thread requests a stack depth greater than the maximum allowable depth of the virtual machine, it will throw Stackoverflowerror * If the virtual machine fails to request enough memory space in the expansion stack, the OutOfMemoryError * VM will be thrown args:-xss128k * @author*/ Public classjavavmstacksof {Private intStacklength =1;  Public voidStackleak () {stacklength++;    Stackleak (); }     Public Static voidMain (string[] args) throws Throwable {javavmstacksof Oom=Newjavavmstacksof (); Try{oom.stackleak (); } Catch(Throwable e) {System. out. println ("Stack Length:"+oom.stacklength); Throwe; }    }}/** * * stack length:2403exception in thread ' main ' java.lang.StackOverflowError at Baby.oom.JavaVMStackSOF.stackLea K (javavmstacksof.java:11) at Baby.oom.JavaVMStackSOF.stackLeak (Javavmstacksof.java:12) at Baby.oom.JavaVMStackSOF.stackLeak (JAVAVMSTACKSOF.JAVA:12) By default, no XSS limit, output length is 8956, add xss128k length bit 2403 */
/** * VM args:-xss2m (this time may be larger) * @author*/ Public classJavavmstackoom {intI=0; Private voidDontstop () { while(true) {              }       }         Public voidStackleakbythread () { while(true) {thread thread=NewThread (NewRunnable () {@Override Public voidrun () {dontstop ();                     }                     }); I++; System. out. println ("i="+i);              Thread.Start (); }       }         Public Static voidMain (string[] args) throws Throwable {Javavmstackoom Oom=NewJavavmstackoom (); Try{oom.stackleakbythread (); } Catch(Throwable e) {System. out. println ("Thread num:"+oom.i); Throwe; }       }}//i=391//Thread num:391//Exception in thread "main" java.lang.OutOfMemoryError:unable to create new native thread

Three, method area overflow

A method area overflow is caused when the run-time pool is too large or too many classes.

import Java.util.arraylist;import java.util.List;/** * VM args:-xx:permsize=10m-xx:maxpermsize=10m * @author*/ Public classRuntimeconstantpooloom { Public Static voidMain (string[] args) {//use list to keep constant pool references to avoid full GC recycle constant pool behaviorlist<string> list =NewArraylist<string>(); //The 10MB permsize is enough to generate oom in the integer range.        inti =0;  while(true) {List.add (string.valueof (i++). Intern ()); }    }}/**exception in thread "main" Java.lang.OutOfMemoryError:PermGen space at Java.lang.String.intern (Native Method) At Baby.oom.RuntimeConstantPoolOOM.main (runtimeconstantpooloom.java:18)*//** * VM Args:-xx:permsize=10m-xx:maxpermsize=10m * @author*/ Public classJavamethodareaoom { Public Static voidMain (string[] args) { while(true) {Enhancer enhancer=Newenhancer (); Enhancer.setsuperclass (oomobject.class); Enhancer.setusecache (false); Enhancer.setcallback (NewMethodinterceptor () {@Override PublicObject Intercept (Object obj, Method method, object[] arg, Methodproxy proxy) throws Throwable {
    //TODO auto-generated Method Stub                    returnproxy.invokesuper (obj, arg);            }            });        Enhancer.create (); }    }    Static classoomobject {}}/* * Exception in thread "main" net.sf.cglib.core.CodeGenerationException: Java.lang.reflect.invocationtargetexception-->null at Net.sf.cglib.core.AbstractClassGenerator.create ( abstractclassgenerator.java:237) at Net.sf.cglib.proxy.Enhancer.createHelper (enhancer.java:377) at Net.sf.cglib.proxy.Enhancer.create (enhancer.java:285) at Baby.oom.JavaMethodAreaOOM.main (Javamethodareaoom.java : Caused by:java.lang.reflect.InvocationTargetException at Sun.reflect.GeneratedMethodAccessor1.invoke (Unknown Source) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (delegatingmethodaccessorimpl.java:25) at Java.lang.reflect.Method.invoke (method.java:597) at Net.sf.cglib.core.ReflectUtils.defineClass (Reflectutils.java : 384) at Net.sf.cglib.core.AbstractClassGenerator.create (abstractclassgenerator.java:219) ... 3 morecaused by:java.lang.OutOfMemoryError:PermGen space at Java.lang.ClassLoader.defineClass1 (Native Method) at J Ava.lang.ClassLoader.defineClassCond (Classloader.java:631) at Java.lang.ClassLoader.defineClass (classloader.java:615) ...  8 more*/

Iv. Direct Memory Overflow
Although allocating memory using Derictbytebuffer also throws a memory overflow exception, it throws an exception when it does not actually request allocation to the operating system, but calculates that the memory is not allocated, and then throws the exception manually. The real way to apply for allocating memory is unsafe.allocatememory ().

import Java.lang.reflect.Field; Import Sun.misc.Unsafe; /** * VM args:-xmx20m-xx:maxdirectmemorysize=10m * @author * Eclipse By default sets these access-restricted APIs to error. Workaround: Add windows->preferences->java-complicer->errors/warnings->deprecated and restricted API, The Forbidden references (access rules) in is set to warning, which can be compiled through. */ Public classDirectmemoryoom {Private StaticFinalint_1MB =1024x768*1024x768;  Public Static voidMain (string[] args) throws Exception {Field Unsafefield= Unsafe.class. Getdeclaredfields () [0]; Unsafefield.setaccessible (true); Unsafeunsafe= (Unsafe) Unsafefield.Get(NULL);  while(true) {            unsafe. Allocatememory (_1MB); }    }}/**exception in thread "main" Java.lang.OutOfMemoryError at Sun.misc.Unsafe.allocateMemory (Native Method) at Baby . Oom. Directmemoryoom.main (directmemoryoom.java:20)*/

Java Memory Overflow Example

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.