Search code examples
javamemoryjvmjvm-hotspot

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) = 16 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 20 byte instead of 16? Why is this happens? Can someone explain to me?


Solution

  • 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)