import java.util.ArrayList;
//java堆溢出:不断生成对象,导致堆内存溢出
public class HeapOOM {
static class OOMObject {
}
public static void main(String[] args) {
ArrayList<OOMObject> list = new ArrayList<>();
while (true){
OOMObject a = new OOMObject();
list.add(a);
}
}
}
/**虚拟机和本地方法栈溢出
* **/
//在单个线程下,无论是由于栈帧太大还是虚拟机容量太小,当内存无法分配的时候,虚拟机都是抛出StackOverflowError异常
public class JavaVMStackSOF {
private int stackLength = 1;
public void stackLeak() {
stackLength++;
stackLeak();
}
public static void main(String[] args) {
JavaVMStackSOF oom = new JavaVMStackSOF();
try {
oom.stackLeak();
} catch (Throwable throwable) {
System.out.println("stack length:" + oom.stackLength);
throw throwable;
}
}
}
//创建线程导致内存溢出异常 OOM
public class JavaVMStackOOM {
private void dontStop() {
while (true) {
}
}
public void stackLeakByThread() {
while (true) {
Thread thread = new Thread(()-> dontStop());
thread.start();
}
}
public static void main(String[] args) {
JavaVMStackOOM oom = new JavaVMStackOOM();
oom.stackLeakByThread();
}
}
//intern()会将首次遇到的字符串实例引用(不是复制字符串)放入常量池,
public class RuntimeConstantPoolOOM {
public static void main(String[] args) {
String str1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern() == str1);
String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern() == str2);
}
}