The deep understanding of Java Virtual Machine (JVM) book introduces JVM memory overflow, which helps you understand the Automatic Memory Management Mechanism of JVM. The following describes several instances.
In the standard description of the Java Virtual Machine, in addition to program counters, runtime time zones such as Java heap, virtual machine stack, and local method zone all have the possibility of an outofmemoryerror.
Java Heap Overflow in 1
// Eclipse-run configurations-VM arguments-Xms20M-xmx20m-xmn10m-XX: + heapdumponoutofmemoryerror
public class HeapOOM{ static class OOMObject { } public static void main(String[] args) { List<OOMObject> list=new ArrayList<OOMObject>(); while(true) { list.add(new OOMObject()); } }}View code
2 Virtual Machine stack and local method Stack Overflow
//-Xss128k
Code 1 generates stackoverflowerror,
public class JVMStacks{ private int stackLength=1; public void stackLeak() { stackLength++; stackLeak(); } public static void main(String[] args) { JVMStacks oom=new JVMStacks(); try { oom.stackLeak(); }catch(Throwable e) { System.out.println(oom.stackLength); throw new RuntimeException(e); } }}View code
//-Xss2m
Code 2 can cause a memory overflow exception, but it often causes your computer to enter a false state.
public void JAVAStack{ private void dostop(){ while(true){};}public void stackLeak(){ while(true){ Thread thread =new Thread(new Runnable(){ public void run(){dostop();}});thread.start();}}public void main(String[] args){JAVAStack oom=new JavaStack();oom.stackLeak();}}View code
3: memory overflow in the pool
//-XX: permsize = 10 m-XX: maxpermsize = 10 m
public class RuntimeConstantPool{ /** * @param args */ public static void main(String[] args) { List<String> list=new ArrayList<String>(); int i=0; while(true) { list.add(String.valueOf(i++).intern()); } }}View code
4. Direct memory overflow on the local machine
/** * VM Args:-Xmx20M -XX:MaxDirectMemorySize=10M * @author zzm */public class DirectMemoryOOM { private static final int _1MB = 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(_1MB); } }}View code
JVM memory overflow