JVM之虚拟机栈和本地方法栈溢出
/**
* -Xss128k
*/
public class JavaVMStackSOF {
private int stackLength = 1;
private 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;
}
}
}
图1 虚拟机栈SOF
实验结果表明:使用-Xss参数减少栈内存,在单个线程的情况下,由于虚拟机栈内存较小,当内存无法分配时,虚拟机报出的是StackOverflowError。
如果测试不限于单线程,通过不断创建线程的方式,是可以产生内存溢出异常的,如下代码所示:
public class JavaVMStackOOM {
private void dontStop() {
while (true) {
}
}
private void stackLeakByThread() {
while (true) {
Thread thread = new Thread(() ->
dontStop());
thread.start();
}
}
public static void main(String[] args) {
JavaVMStackOOM oom = new JavaVMStackOOM();
oom.stackLeakByThread();
}
}