1 堆的特点

使用new关键字创建的对象都会使用堆。

特点:

  • 线程共享,堆中的对象需要考虑线程安全问题。
  • 具有垃圾回收机制。
2 内存溢出
public class MemoryOverFlow {
    public static void main(String[] args) {
        int i = 0;
        String a = "hello";
        List list = new ArrayList();
        try {
            while (true) {
                list.add(a);
                a = a + a;
                i++;
            }
        } catch (Throwable e) { //使用Throwable,如果使用Exception包不住Error,i无法被打印出来
           e.printStackTrace();
           System.out.println(i);
        }

    }
}

出现OutOfMemoryError

java.lang.OutOfMemoryError: Overflow: String length out of range
        at java.base/java.lang.StringConcatHelper.checkOverflow(StringConcatHelper.java:57)
        at java.base/java.lang.StringConcatHelper.mix(StringConcatHelper.java:138)
        at java.base/java.lang.StringConcatHelper.simpleConcat(StringConcatHelper.java:420)
        at MemoryOverFlow.main(MemoryOverFlow.java:12)
28

另:参数-Xmx可以设置jvm内存空间大小,排查堆内存问题时可以将其设置得比较小(如8m),更容易暴露出内存溢出问题。