1JVM内存四大类型问题:Heap、Stack、Contant、DirectMemory

第一 heap 堆溢出:

heap中只能保存对象,对象存储过多会报错 java heap space

测试时修改JVM的默认参数:


 代码:

import java.util.ArrayList;
import java.util.List;


class Person{ }


public class HelloHeapOutOfMemory {

public static void main(String[] args) {
System.out.println("HelloHeapOutOfMemory");
List<Person> persons = new ArrayList<Person>();
int counter = 0;
      while(true){
      persons.add(new Person());
      System.out.println("Instance: " + (++counter));
      }


}


}

结果:10M空间在存储36W个空对象后报错;



第二:stack是线程私有,在主线程中运行其他线程会报错:stackOverFlowError

代码:

package com.dt.spark.jvm.basics;


public class HelloStackOverFlow {
private int counter;


  


    public void count() {


       counter++;


       count();


    }


public static void main(String[] args) {
System.out.println("HelloStackOverFlow");


HelloStackOverFlow helloStackOverFlow = new HelloStackOverFlow();
try {
helloStackOverFlow.count();
} catch (Exception e) {
e.printStackTrace();
throw e;
}

}


}

结果:


3.ConstantOutOfMemory 当常量里面存储内容超出存储空间时会报错 GC overhead limit exceeded

测试代码:


package com.dt.spark.jvm.basics;


import java.util.ArrayList;
import java.util.List;


public class HelloConstantOutOfMemory {


public static void main(String[] args) {
try {


          List<String> stringList = new ArrayList<String>();


          int item = 0;


          while(true){


             stringList.add(String.valueOf(item++).intern());


          }


      } catch (Exception e) {


          e.printStackTrace();


          throw e;


      }


}


}


结果:


4.java.lang.OutOfMemoryError: Direct buffer memory

代码:

package com.dt.spark.jvm.basics;


import java.nio.ByteBuffer;


public class HelloDirectMemoryOutOfmemory {
private static final int ONE_GB = 1024*1024*1024;


private static int count = 1;


public static void main(String[] args) {
 try {           


          while (true) {


             ByteBuffer buffer = ByteBuffer.allocateDirect(ONE_GB);


             count++;


          }


      } catch (Exception e) {


          System.out.println("Exception:instance created "+count);


          e.printStackTrace();


      } catch (Error e) {


          System.out.println("Error:instance created "+count);


          e.printStackTrace();


      }
}


}

结果:


注意:测试时,把jvm的临时改为-verbose:gc -Xms10M -Xmx10M -Xss128k -XX:+PrintGCDetails

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值