简体   繁体   中英

Calculating the Memory Usage of java Object with VisualVM Heap Dump does not match with theoretical approach

All I come with a simple question. According to the java docs and many articles about java memory object layout if we have a class with one int variable the total memory consumption for that object will be:

  • 8 byte for the heading
  • 4 byte for the int
  • 4 byte padding (to round the total up to be multiple of 8 bytes) = bytes total 字节
public class Ab {        
    int b;
}

public static void main(String args[]) throws InterruptedException {
    Ab ab = new AB();  
}  

My problem now is that when I used the Visual vm and look at the Heap dump to observe this the theoretical approach I noticed that the memory consumption for that object was byte instead of ? 字节而不是字节? Why is this happens? Can someone explain to me?

Using the Java Object Layout tool I received the following output:

 OFFSET  SIZE   TYPE DESCRIPTION        VALUE
      0    12        (object header)    N/A
     12     4    int Ab.b               N/A

Instance size: 16 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

And with the -XX:-UseCompressedOops VM option (disable compressed references):

 OFFSET  SIZE   TYPE DESCRIPTION                                VALUE
      0    16        (object header)                            N/A
     16     4    int Ab.b                                       N/A
     20     4        (loss due to the next object alignment)

Instance size: 24 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total

Java environment:

java version "11" 2018-09-25
Java(TM) SE Runtime Environment 18.9 (build 11+28)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)

According to "Object header layout" section in hotspot documentation: https://wiki.openjdk.java.net/display/HotSpot/CompressedOops

"An object header consists of a native-sized mark word, a klass word, a 32-bit length word (if the object is an array), a 32-bit gap (if required by alignment rules), and then zero or more instance fields, array elements, or metadata fields.

So it would mean that in your case it looks like this:

  • 8 byte for mark word (8 byte on 64 bit architectures)
  • 4 byte for klass word (because by default compressed oops are used)
  • 8 byte gap (that is where your int field is stored)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM