stack的内存溢出demo,无限递归:
public class StackOOM { private static void fun(){ fun(); } /** * VM arg -Xss128K * @param args */ public static void main(String[] args) { fun(); } }
direct memory:
public class DirectMemoryOOM { static int ONE_MB = 1024*1024; /** * -XX:MaxDirectMemorySize=5M * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { List<ByteBuffer> list = new ArrayList<ByteBuffer>(); for(int i=0; i<ONE_MB;++i){ ByteBuffer buffer = ByteBuffer.allocateDirect(ONE_MB*128); list.add(buffer); System.out.println("分派第"+(i+1)+" 个128MB"); } } }
heap:
public class HeapOOM { static int MB = 1024*1024; /** * -Xmx16M * @param args */ public static void main(String[] args) { List<Object> list = new ArrayList<Object>(); for(int i=0; i<1000; ++i){ ByteBuffer bb = java.nio.ByteBuffer.allocate(MB); list.add(bb); System.out.println("分派第"+(i+1)+" MB"); } } }
常量池:
public class ConstantPoolOOM { /** * -XX:MaxPermSize=10M * @param args */ public static void main(String[] args) { List<Object> list = new ArrayList<Object>(); for(int i=0; i<1000; ++i){ list.add(UUID.randomUUID().toString().intern()); System.out.println("分派第"+(i+1)+" 个"); } } }
方法区(借助cglib,大量的字节码加强,从而撑爆方法区):
public class MethodAreaOOM { static class OOMObject { } /** * -XX:MaxPermSize=10M * @param args */ public static void main(String[] args) { for (int i = 0; i < 9999; ++i) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(OOMObject.class); enhancer.setUseCache(false); enhancer.setCallback(new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { return proxy.invokeSuper(obj, args); } }); enhancer.create(); } } }
具体代码见github:https://github.com/emmerichLuang/differentOOM