栈的大小用-Xss来设置
- 当线程请求的栈深度大于虚拟机所允许的最大深度, 将抛出StackOverflowError异常
public class StackOverflowErrorTest {
static int times = 1;
public static void main(String[] args) {
try {
self();
//捕获error而非Exception
} catch (Error e) {
System.out.println(String.format("递归%s次",times));
throw e;
}
}
private static void self() {
times++;
self();
}
}
右键设置栈大小
启动main方法
设置-Xss 160是我的操作系统下的最小值,不同的操作系统不同的jdk的版本的最小值可能不一样,如果小于了最小值可能会无法启动
- 《Java虚拟机规范》 允许Java虚拟机实现自行选择是否支持栈内存大小的动态扩展,HotSpot虚拟机不支持扩展,如果虚拟机的栈内存允许动态扩展,当扩展容量容量无法申请到足够内存时,将抛出OutOfMemoryError异常。局部变量过多,超过了栈内存大小的话,在HotSpot中依然会抛出StackOverflowError
public static void main(String[] args) {
try {
test();
} catch (Error error) {
System.out.println(String.format("递归%s次", times));
throw error;
}
}
private static void test() {
long l1 = 0;
long l2 = 0;
long l3 = 0;
long l4 = 0;
long l5 = 0;
long l6 = 0;
long l7 = 0;
long l8 = 0;
long l9 = 0;
long l10 = 0;
long l11 = 0;
long l12 = 0;
long l13 = 0;
long l14 = 0;
long l15 = 0;
test();
}
由于在下家里的电脑虚拟机是HotSpot,抛出的异常始终是StackOverflowError
以下截图截自相关资料,类似代码在Classic虚拟机的执行结果



