问题背景
上周,同事写了一段ConcurrentHashMap的测试代码,说往map里放了32个元素就内存溢出了,我大致看了一下他的代码及运行的jvm参数,觉得很奇怪,于是就自己捣鼓了一下。首先上一段代码:
1 public class MapTest { 2 3 public static void main(String[] args) { 4 System.out.println("Before allocate map, free memory is " + Runtime.getRuntime().freeMemory()/(1024*1024) + "M"); 5 Map<String, String> map = new ConcurrentHashMap<String, String>(2000000000); 6 System.out.println("After allocate map, free memory is " + Runtime.getRuntime().freeMemory()/(1024*1024) + "M"); 7 8 int i = 0; 9 try { 10 while (i < 1000000) { 11 System.out.println("Before put the " + (i + 1) + " element, free memory is " + Runtime.getRuntime().freeMemory()/(1024*1024) + "M"); 12 map.put(String.valueOf(i), String.valueOf(i)); 13 System.out.println("After put the " + (i + 1) + " element, free memory is " + Runtime.getRuntime().freeMemory()/(1024*1024) + "M"); 14 i++; 15 } 16 } catch (Exception e) { 17 e.printStackTrace(); 18 } catch (Throwable t) { 19 t.printStackTrace(); 20 } finally { 21 System.out.println("map size is " + map.size()); 22 } 23 } 24 25 }
执行时加上jvm执行参数 -Xms512m -Xmx512m ,执行结果: