当堆内存(Heap Space)没有足够空间存放新创建的对象时,就会抛出 java.lang.OutOfMemoryError:Javaheap space 错误
//-Xmx8m
public class Demo {
public static void main(String[] args) {
int i = 0;
try {
ArrayList<String> list = new ArrayList<>();
String a = "hello";
while (true){
list.add(a); //hello,hellohello,hellohellohello
a = a+a; //hellohellohello
i++;
}
} catch (Throwable e) {
e.printStackTrace();
System.out.println(i);
}
}
}



栈内存溢出演示
public class Demo {
private static int count;
public static void main(String[] args) {
try {
method1();
} catch (Throwable e) {
e.printStackTrace();
System.out.println(count);
}
}
private static void method1(){
count++;
method1();
}
}


该错误表示永久代(Permanent Generation)已用满,通常是因为加载的 class 数目太多或体积太大。
1.8以前会导致永久代内存溢出


1.8之后会导致元空间内存溢出


场景
spring mybatis
Direct Memory


内存溢出
/**
* 演示直接内存溢出
*/
public class Demo {
static int _100Mb = 1024 * 1024 * 100;
public static void main(String[] args) {
List<ByteBuffer> list = new ArrayList<>();
int i = 0;
try {
while (true) {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_100Mb);
list.add(byteBuffer);
i++;
}
} finally {
System.out.println(i);
}
// 方法区是jvm规范, jdk6 中对方法区的实现称为永久代
// jdk8 对方法区的实现称为元空间
}
}
3.6g没了
