A a=new A(); ClassLayout layout = ClassLayout.parseInstance(a); System.out.println(layout.toPrintable());
输出结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Running 64-bit HotSpot VM. # Using compressed oop with 3-bit shift. # Using compressed klass with 3-bit shift. # WARNING | Compressed references base/shifts are guessed by the experiment! # Objects are 8 bytes aligned. # Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] # Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
com.hardydou.jmm.ObjectSize$A object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1) 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0) 8 4 (object header) 16 f0 00 f8 (00010110 11110000 00000000 11111000) (-134156266) 12 4 (loss due to the next object alignment) Instance size: 16 bytes Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
增加放方法、静态属性后
1 2 3 4 5 6 7 8
public static class A { static int a; private void m1(){} private void m2(){} } A a=new A(); ClassLayout layout = ClassLayout.parseInstance(a); System.out.println(layout.toPrintable());
输出结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Running 64-bit HotSpot VM. # Using compressed oop with 3-bit shift. # Using compressed klass with 3-bit shift. # Objects are 8 bytes aligned. # Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] # Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
com.hardydou.jmm.ObjectSize$A object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1) 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0) 8 4 (object header) 16 f0 00 f8 (00010110 11110000 00000000 11111000) (-134156266) 12 4 (loss due to the next object alignment) Instance size: 16 bytes Space losses: 0 bytes internal + 4 bytes external = 4 bytes total