欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

堆中堆溢出,栈溢出实例,永久区溢出

程序员文章站 2022-04-18 18:32:57
...

1.堆溢出

main:
public class HeapOOM {
   
  public static void main(String[] args) {
    List<UserBean> users = new ArrayList<UserBean>();
    while (true) {
      users.add(new UserBean());
    }
  }

bean:
public class UserBean {
  String name;
  int age;
}
然后在运行的时候设置jvm参数
-xmx1m -Xms1m -Xmn1m

运行结果:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
  at java.util.Arrays.copyOf(Unknown Source)
  at java.util.Arrays.copyOf(Unknown Source)
  at java.util.ArrayList.grow(Unknown Source)
  at java.util.ArrayList.ensureExplicitCapacity(Unknown Source)
  at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
  at java.util.ArrayList.add(Unknown Source)
  at oom.HeapOOM.main(HeapOOM.java:21)

2.栈溢出

main:

public static void main(String[] args) {
    Recursion recursion = new Recursion();
    try {
      recursion.recursionself();
    } catch (Throwable e) {
      System.out.println("current value :" + recursion.currentValue);
      throw e;
    }
  }

bean:
public class Recursion {
    public int currentValue = 0;

    public void recursionself() {
        currentValue += 1;
        recursionself();
    }
}

设置参数 -Xss100k
结果:
Exception in thread "main" java.lang.*Error
  at testbean.Recursion.recursionself(Recursion.java:7)
  at testbean.Recursion.recursionself(Recursion.java:8)
  at testbean.Recursion.recursionself(Recursion.java:8)
  at testbean.Recursion.recursionself(Recursion.java:8)
  at testbean.Recursion.recursionself(Recursion.java:8)
  at testbean.Recursion.recursionself(Recursion.java:8)

 3.永久区溢出:

第三个异常是关于perm的异常内容,我们需要的是设置方法区的大小,实现方式是通过设置-XX:PermSize和-XX:MaxPermSize参数
如果程序加载的类过多,例如tomcatweb容器,就会出现PermGen space异常,如果我将HeapOOM类的运行时的XX:PermSize设置为1M
那么程序就不会执行成功,执行的时候出现如下异常:
Error occurred during initialization of VM
java.lang.OutOfMemoryError: PermGen space
  at sun.misc.Launcher$ExtClassLoader.getExtClassLoader(Unknown Source)
  at sun.misc.Launcher.<init>(Unknown Source)
  at sun.misc.Launcher.<clinit>(Unknown Source)
  at java.lang.ClassLoader.initSystemClassLoader(Unknown Source)
  at java.lang.ClassLoader.getSystemClassLoader(Unknown Source)