第一 heap 堆溢出:
heap中只能保存对象,对象存储过多会报错 java heap space
测试时修改JVM的默认参数:
代码:
import java.util.ArrayList;
import java.util.List;
class Person{ }
public class HelloHeapOutOfMemory {
public static void main(String[] args) {
System.out.println("HelloHeapOutOfMemory");
List<Person> persons = new ArrayList<Person>();
int counter = 0;
while(true){
persons.add(new Person());
System.out.println("Instance: " + (++counter));
}
}
}
结果:10M空间在存储36W个空对象后报错;
第二:stack是线程私有,在主线程中运行其他线程会报错:stackOverFlowError
代码:
package com.dt.spark.jvm.basics;
public class HelloStackOverFlow {
private int counter;
public void count() {
counter++;
count();
}
public static void main(String[] args) {
System.out.println("HelloStackOverFlow");
HelloStackOverFlow helloStackOverFlow = new HelloStackOverFlow();
try {
helloStackOverFlow.count();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
结果:
3.ConstantOutOfMemory 当常量里面存储内容超出存储空间时会报错 GC overhead limit exceeded
测试代码:
package com.dt.spark.jvm.basics;
import java.util.ArrayList;
import java.util.List;
public class HelloConstantOutOfMemory {
public static void main(String[] args) {
try {
List<String> stringList = new ArrayList<String>();
int item = 0;
while(true){
stringList.add(String.valueOf(item++).intern());
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
结果:
4.java.lang.OutOfMemoryError: Direct buffer memory
代码:
package com.dt.spark.jvm.basics;
import java.nio.ByteBuffer;
public class HelloDirectMemoryOutOfmemory {
private static final int ONE_GB = 1024*1024*1024;
private static int count = 1;
public static void main(String[] args) {
try {
while (true) {
ByteBuffer buffer = ByteBuffer.allocateDirect(ONE_GB);
count++;
}
} catch (Exception e) {
System.out.println("Exception:instance created "+count);
e.printStackTrace();
} catch (Error e) {
System.out.println("Error:instance created "+count);
e.printStackTrace();
}
}
}
结果:
注意:测试时,把jvm的临时改为-verbose:gc -Xms10M -Xmx10M -Xss128k -XX:+PrintGCDetails