Mixalis Navridis
Mixalis Navridis

Reputation: 329

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:

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?

Upvotes: 2

Views: 1438

Answers (2)

Oleksandr Pyrohov
Oleksandr Pyrohov

Reputation: 16276

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)

Upvotes: 5

Guts
Guts

Reputation: 768

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)

Upvotes: 1

Related Questions