JAVA内存异常实例
1.java堆溢出OutOfMemoryError
import java.util.ArrayList;
import java.util.List;
/*
* VM Args: -Xms20m -Xmx20m -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());
}
}
}
2.虚拟机栈和本地方法溢出
/*
* VM Args: -Xss128k
*/
public class JavaVMStackSOF {
private int stackLength = 1;
public void stackLeak(){
stackLength++;
stackLeak();
}
public static void main(String[] args) throws Throwable {
JavaVMStackSOF com = new JavaVMStackSOF();
try {
com.stackLeak();
} catch (Exception e) {
System.out.println("stack length:" +
com.stackLength);
throw e;
}
}
}
3.运行时常量溢出
import java.util.ArrayList;
import java.util.List;
import java.util.ArrayList;
import java.util.List;
/*
* VM Args: -XX:PermSize=10M -XX:MaxPermSize=10M
*/
public class RuntimeConstantPoolOOM {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
int i = 0;
while(true){
//System.out.println("***i:" + i++);
list.add(String.valueOf(i++).intern());//不加intern这个方法就不会把字符串放到常量池
}
}