/**
* 区域虚拟机栈、本地方法栈
* VM参数 : -Xss128k
* -Xss栈内存容量
* 单线程下只会出现StackOverflowError异常
* */
public class Main {
public static void main(String[] args) {
StackTest st = new StackTest();
try {
st.stackTest();
} catch (Throwable e){
System.out.println("stackLength:" + st.stackLength);
throw e;
}
}
}
class StackTest{
//栈的深度
public int stackLength = 1;
public void stackTest(){
stackLength++;
stackTest();
}
}
运行结果:
stackLength:1002
Exception in thread "main" java.lang.StackOverflowError
at sun.misc.Unsafe.compareAndSwapLong(Native Method)
at java.util.concurrent.ConcurrentHashMap.addCount(ConcurrentHashMap.java:2259)
at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1070)
at java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1535)
at java.lang.ClassLoader.getClassLoadingLock(ClassLoader.java:463)
at java.lang.ClassLoader.loadClass(ClassLoader.java:404)
at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at StackTest.stackTest(Main.java:27)
at StackTest.stackTest(Main.java:27)
/**
* VM参数 : -Xss2m (栈内存分配越大,越容易发生内存溢出)
* 多线程可以导致OutOfMemoryError
* 此方法可能导致系统假死,注意保存
*
* */
public class Main {
public static void main(String[] args) {
StackOOMTest st = new StackOOMTest();
st.stackLeakByThread();
}
}
class StackOOMTest{
private void dontStop(){
while (true){
}
}
public void stackLeakByThread(){
while (true) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
dontStop();
}
});
thread.start();
}
}
}
运行结果:
Exception in thread"main"java.lang.OutOfMemoryError:unable to create new native thread