"How much space does an empty Object occupy?"

A Java programmer who has been working for 5 years is directly fooled.

Hi, my name is Mic, a Java programmer who has been working for 14 years.

I have organized the text version of this question into a 15W word interview document, and you can scan the end of the article to get it.

Check out the experts' answers below.

Expert:

When the compressed pointer is turned on, Object will occupy 12 bytes by default, but in order to avoid false sharing problems, JVM will fill in multiples of 8 bytes, so it will fill 4 bytes into 16 bytes. length.

In the case of closing the compressed pointer, Object will occupy 16 bytes by default, and 16 bytes are exactly an integer multiple of 8, so no padding is required.

In the HotSpot virtual machine, the memory layout of an object in the heap memory is represented by the OOP structure.
It is mainly divided into three parts.

image-20220728160303222

  • Object header, including Markword, class element pointer, and array length. Markword is used to store relevant data when the object is running, such as hashCode, GC generation age, etc.

    It occupies 8 bytes in a 64-bit operating system, and 4 bytes in a 32-bit operating system. The class element pointer points to which class the current instance object belongs to. It occupies 4 bytes when the pointer compression is enabled, and 8 bytes when it is not enabled. The length of the byte array only exists in the object array, accounting for 4 bytes

  • Instance data, which stores field information in an object
  • Alignment padding, the size of Java objects needs to be aligned according to 8 bytes or a multiple of 8 bytes to avoid false sharing problems.

image-20220728173019988

Therefore, an empty object, with compressed pointers turned on, occupies 16 bytes

The Markword occupies 8 bytes, the class element pointer occupies 4 bytes, and the alignment padding occupies 4 bytes.

Summarize

This question not only examines the basics of the JVM, but also examines the applicant's understanding of the JVM's memory layout of objects.

The understanding of memory layout is mainly to help us better solve practical problems in JVM applications

Friends who like it remember to like, favorite and follow! ! !

file

Copyright notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated. Please indicate the source for Mic带你学架构 !
If this article is helpful to you, please help to follow and like, your persistence is the driving force for my continuous creation. Welcome to follow the WeChat public account of the same name to get more technical dry goods!

跟着Mic学架构
810 声望1.1k 粉丝

《Spring Cloud Alibaba 微服务原理与实战》、《Java并发编程深度理解及实战》作者。 咕泡教育联合创始人,12年开发架构经验,对分布式微服务、高并发领域有非常丰富的实战经验。