1、最简单的内存溢出
public class HeapOOM {
HeapOOM[] testlist= new HeapOOM[100000];
public static void main(String[] args) {
List<HeapOOM> list= new ArrayList<HeapOOM>();
while(true){
list.add(new HeapOOM());
}
}
}
2、虚拟机栈和本地方法栈溢出(-Xss:栈内存容量)
两种异常:
如果线程请求的深度大于虚拟机所允许的最大深度,将抛出StackOverflowError异常。
如果虚拟机在扩展栈时无法申请到足够的内存空间,则抛出OutOfMemoryError异常。
单线程时栈溢出:
public class StackOverflow {
private int stackLength = 1;
public void stackLeak(){
stackLength++;
stackLeak();
}
public static void main(String[] args) throws Throwable {
StackOverflow stackOverflowError = new StackOverflow();
try {
stackOverflowError.stackLeak();
}catch (Throwable e){
System.out.println("stack 深度:"+stackOverflowError.stackLength);
throw e;
}
}
}
多线程下的栈溢出:
通过不断建立线程的方式可以产生内存溢出异常。在这种情况下,为每个线程的栈分配的内存越大,越容易产生内存溢出异常。
原因是:操作系统分配给每个进程的内存是有限制的,譬如32位的Windows限制为2GB。虚拟机提供了参数来控制Java堆和方法区的两部分内存的最大值。剩余的内存为2GB减去Xmx(最大堆容量),再减去MaxPermSize(最大方法区容量)
public class StackOverThread {
private void donnotStop(){
while (true){
donnotStop();
}
}
public void stackLeakByThread(){
while (true){
Thread thread = new Thread(new Runnable() {
public void run() {
donnotStop();
}
});
thread.start();
}
}
public static void main(String[] args) {
StackOverThread stackOverThread = new StackOverThread();
stackOverThread.stackLeakByThread();
}
}
3、
原文:https://www.cnblogs.com/yaohuiqin/p/9550254.html