java对象占用内存大小计算方法

public static void main(String[] args) {

Map testMap = new HashMap();
Product p= null;
long start = 0;
long end = 0;
System.gc();
start = Runtime.getRuntime().freeMemory();
System.out.println("+++++++++++++++++测试HashMap开始++"+Formater.formatAsLong(new Date())+"++++++++++++++++");
for(int i=0;i<20000;i++){
p=new Product();//20个属性的大对象
p.setProductCode(i+"dfsdf");
p.setProductName(i+"namessssssdfsdfssss");
testMap.put(i, p);
}
//servletContext.setAttribute("productHashMap",testMap);
System.gc();
end = Runtime.getRuntime().freeMemory();
System.out.println("一个HashMap对象占内存:" + (start-end)/1024.0/1024.0);//MB
// 测试 2万条数据 占26.96MB空间
// 测试 5万条数据比较轻松 占73.8MB空间
System.out.println("+++++++++++++++++测试HashMap结束+++++"+Formater.formatAsLong(new Date())+"++++Size:"+testMap.size()+"++++++++++++");

}

你可能感兴趣的:(java)