查看普通java对象的内部布局工具JOL(JAVA OBJECT LAYOUT)
使用此工具可以查看new出来的一个java对象的内部布局,以及一个普通的java对象占用多少字节。
导入依赖或者jar包
1 2 3 4 5 6 7 8
| <dependency> <groupId>org.openjdk.jol</groupId> <artifactId>jol-core</artifactId> <version>0.9</version> <scope>provided</scope> </dependency>
|
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
public class JOL { public static void main(String[] args) { Object o = new Object(); System.out.println(ClassLayout.parseInstance(o).toPrintable());
synchronized (o){ System.out.println(ClassLayout.parseInstance(o).toPrintable()); } } }
|
打印:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| java.lang.Object 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) e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243) 12 4 (loss due to the next object alignment) Instance size: 16 bytes Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
java.lang.Object object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 28 f2 5a 03 (00101000 11110010 01011010 00000011) (56291880) 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0) 8 4 (object header) e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243) 12 4 (loss due to the next object alignment) Instance size: 16 bytes Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
|
前面两行是java对象头的Mark Word共占8个字节,第三行是java对象头的Klass Pointer类指针,本来也是占8个字节,因JDK默认开启类指针压缩所以占4个字节,总共12个字节,又因12不能被8整除,所有最后又加了四个空字节.所以java中new一个空对象总共占16个字节.
涉及内容:jVM对象的内存布局,请看博客: