随笔。记录各类型在堆内存中占用内存空间大小的理解:
引用类型在堆中占用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)
“def new generation total 9216K, used 5136K [0x33400000, 0x33e00000, 0x33e00000)”从此处知,
占用的内容空间是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内存发现,
“def new generation total 9216K, used 3088K [0x33400000, 0x33e00000, 0x33e00000)”
占用的内存空间为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)