1. 程式人生 > >JVM heap記憶體分配(1)

JVM heap記憶體分配(1)

隨筆。記錄各型別在堆記憶體中佔用記憶體空間大小的理解:

引用型別在堆中佔用4位元組,

byte,boolean基本型別在堆中佔用1位元組,

char,short基本型別在堆中佔用2位元組,

int,float基本型別在堆中佔用4位元組,

long,double基本型別在堆中佔用8位元組。

用程式碼驗證下,以下程式碼的vm引數為

-Xmx20m -Xms20m  -XX:+HeapDumpOnOutOfMemoryError

-XX:HeapDumpPath=d:\dump -XX:+PrintGCDetails -Xmn10M

-Xmx20m:JVM heap 最大分配堆記憶體為20m

-Xms20m:JVM heap 初始分配堆記憶體為20m

-XX:+HeapDumpOnOutOfMemoryError   表示記憶體溢位時,dump當前的堆轉儲快照

-XX:HeapDumpPath=d:\dump   堆轉儲快照的存放路徑

-XX:+PrintGCDetails    JVM 發現GC時列印GC日誌

-Xmn10M:年輕代堆的大小為10m

1、測試new String[1024*1024]佔用堆記憶體空間的大小

public class TestOutOfMemory {
     
     public static void main(String[] args) {
          int v = 0;
          while(v<1) {
              String[] a = new String[1024*1024];
              System.out.println(v++);
          }
     }
}

列印heap記憶體發現

Heap
 def new generation   total 9216K, used 5136K [0x33400000, 0x33e00000, 0x33e00000)
  eden space 8192K,  62% used [0x33400000, 0x33904170, 0x33c00000)
  from space 1024K,   0% used [0x33c00000, 0x33c00000, 0x33d00000)
  to   space 1024K,   0% used [0x33d00000, 0x33d00000, 0x33e00000)
 tenured generation   total 10240K, used 0K [0x33e00000, 0x34800000, 0x34800000)
   the space 10240K,   0% used [0x33e00000, 0x33e00000, 0x33e00200, 0x34800000)
 compacting perm gen  total 12288K, used 183K [0x34800000, 0x35400000, 0x38800000)
   the space 12288K,   1% used [0x34800000, 0x3482dc68, 0x3482de00, 0x35400000)
    ro space 10240K,  44% used [0x38800000, 0x38c7c1d8, 0x38c7c200, 0x39200000)
    rw space 12288K,  52% used [0x39200000, 0x398440c0, 0x39844200, 0x39e00000)

佔用的內容空間是4M。說明new String()在堆中佔用的空間是4位元組。

2、測試new char[1024*1024]佔用堆記憶體空間的大小

public class TestOutOfMemory {
     
     public static void main(String[] args) {
          int v = 0;
          while(v<1) {
              char[] a = new char[1024*1024];
              System.out.println(v++);
          }
     }
}

列印heap記憶體發現,佔用的記憶體空間為2M,說明new char()在堆中佔用的空間是2位元組。

0
Heap
 def new generation   total 9216K, used 3088K [0x33400000, 0x33e00000, 0x33e00000)
  eden space 8192K,  37% used [0x33400000, 0x33704098, 0x33c00000)
  from space 1024K,   0% used [0x33c00000, 0x33c00000, 0x33d00000)
  to   space 1024K,   0% used [0x33d00000, 0x33d00000, 0x33e00000)
 tenured generation   total 10240K, used 0K [0x33e00000, 0x34800000, 0x34800000)
   the space 10240K,   0% used [0x33e00000, 0x33e00000, 0x33e00200, 0x34800000)
 compacting perm gen  total 12288K, used 183K [0x34800000, 0x35400000, 0x38800000)
   the space 12288K,   1% used [0x34800000, 0x3482dc60, 0x3482de00, 0x35400000)
    ro space 10240K,  44% used [0x38800000, 0x38c7c1d8, 0x38c7c200, 0x39200000)
    rw space 12288K,  52% used [0x39200000, 0x398440c0, 0x39844200, 0x39e00000)