1、HotSpot虚拟机中并不区分虚拟机栈和本地方法栈,
-Xoss参数 设置本地方法栈的大小;
-Xss参数 设置栈容量;
注意:
1、如果线程请求的栈深度大于虚拟机所允许的最大深度,将抛出StackOverflowError异常。
2、如果虚拟机在扩展时无法申请到足够的内存空间,则抛出OutofMemoryError异常。
测试:StackOverflowError
Run configurations参数设置为:-verbose:gc -Xms20M -Xmx20M -Xmn10M -Xss128k
public class JavaVMStackSOF {
private int stackLength = 1;
public void stackLeak() {
stackLength++;
stackLeak();
}
public static void main(String[] args) throws Throwable {
try {
stackLeak();
} catch (Throwable e) {
System.out.println("stack length:" + oom.stackLeak());
throw e;
}
}
}
运行结果:
stack length:11423
Exception in thread "main" java.lang.StackOverflowError
at test.com.jvm.
at test.com.jvm.
实验结果表明:
在单个线程下,无论是由于栈针太大,还是虚拟机栈容量不足,当内存无法分配的时候,虚拟机就会抛出StackOverflowError;
----------------------------------------------------------------------------------------------------------
模拟OutofMemoryError异常:
run configurations参数:-verbose:gc -Xms20M -Xmx20M -Xmn10M -Xss2M
测试代码如下:
public class JavaVMStackOOM {
private void dontStop() {
while (true) {
}
}
public void stackLeakByThread() {
while (true) {
Thread thread = new Thread(new Runnable() {
public void run() {
dontStop();
}
});
thread.start();
}
}
public static void main(String[] args0) {
oom.stackLeakByThread();
}
}
运行结果:Exception in thread"main" java.lang.OutOfMemoryError:unable to create new native thread