原创

Java常见内存崩溃异常示例

堆溢出


class OOMTest {
}

/**
 * 堆溢出
 */
public static void heapOOMTest() {
  ArrayList list = new ArrayList();
  while (true) {
    list.add(new OOMTest());
  }
}

虚拟机栈溢出

private static int stackLength = 1;
/**
 * 虚拟机栈溢出
 */
public static void jvmStackOOMTest() {
  stackLength++;
  jvmStackOOMTest();
}

本地方法栈溢出

/**
 * 本地方法栈溢出,win系统不要执行,演示一下容易雪崩
 */
public static void nativeStackOOMTest() {
	while (true) {
	Thread t = new Thread(new Runnable() {
		@Override
		public void run() {
			dontStop();
		}
		});
		t.start();
	}
}


private static void dontStop() {
	while (true) {
	}
}



运行时常量池溢出

/**
 * 运行时常量池溢出 目前只再jdk1.7以前会报错,之后不会溢出
 */
public static void runTimeConstantPoolOOM() {
  List<String> list = new ArrayList<String>();
  int i = 0;
  while (true) {
    list.add(String.valueOf(i++).intern());
  }
}

使用 cglib 方法去出现内存溢出

/**
 * 使用cglib方法去出现内存溢出
 */
public static void javaMethodAreaOOM() {
	while (true) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(OOMObject.class);
		enhancer.setUseCache(false);
		enhancer.setCallback(new MethodInterceptor() {
		@Override
		public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws   Throwable {
			return proxy.invokeSuper(obj, args);
			}
		});
		enhancer.create();
	}
}

static class OOMObject {

}

本机内存溢出

private static final int _1MB = 1024 * 1024;
/**
 * 本机内存溢出   注意需要引用 import sun.misc.Unsafe;
 * @throws Exception
 * @throws IllegalArgumentException
 */
public static void directMemoryOOM() throws IllegalArgumentException, Exception {
  Field unsafeFiled = Unsafe.class.getDeclaredFields()[0];
  unsafeFiled.setAccessible(true);
  Unsafe unsafe = (Unsafe)unsafeFiled.get(null);
  while (true) {
    unsafe.allocateMemory(_1MB);
  }
}

元空间溢出

/**
 * 为了快速溢出,设置参数:-XX:MetaspaceSize=8m -XX:MaxMetaspaceSize=80m,
 * 
 */ 
 
 public static void main(String[] args) {  
       try {  
            //准备url  
            URL url = new File("D:/58workplace/11study/src/main/java/jdk8").toURI().toURL();  
            URL[] urls = {url};  
            //获取有关类型加载的JMX接口  
            ClassLoadingMXBean loadingBean = ManagementFactory.getClassLoadingMXBean();  
            //用于缓存类加载器  
            List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();  
            while (true) {  
                //加载类型并缓存类加载器实例  
                ClassLoader classLoader = new URLClassLoader(urls);  
                classLoaders.add(classLoader);  
                classLoader.loadClass("ClassA");  
                //显示数量信息(共加载过的类型数目,当前还有效的类型数目,已经被卸载的类型数目)  
                System.out.println("total: " + loadingBean.getTotalLoadedClassCount());  
                System.out.println("active: " + loadingBean.getLoadedClassCount());  
                System.out.println("unloaded: " + loadingBean.getUnloadedClassCount());  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
正文到此结束