您的位置:首页 > 其它

JVM StackOverflowError vs. OutOfMemoryError

2016-08-26 22:46 555 查看
if the computation in a thread needs a larger Java Virtual Machine stack than is permitted, the Java Virtual Machine throws a StackOverflowError;

if Java Virtual Machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java Virtual Memory stack for a new thread, the Java Virtual Machine throws an OutOfMemoryError.

Example of StackOverflowError: limit the size of a thread's stack size and the do a deep recursion

public class Main {

public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
{
System.out.println(fact(1<<15));
}
}
private long fact(int n) {
return n < 2 ? 1 : n * fact(n-1);
}
}, "thread", 1<<20).start();
}
}


Example of OutOfMemoryError: limit -Xmx and create large objects (like using StringBuilder)

public class Main2 {

public static void main(String[] args) {
new Thread(null, () -> {
{
StringBuilder builder = new StringBuilder();
for (int cnt = 0; cnt < 100000000; cnt++) {
builder.append(cnt);
}

try {
Thread.sleep(15000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "thread", 1 << 20).start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐