Why VisualVm and JOL tools give different results for object size

658 Views Asked by At

I've tried to measure size of one instance of the class A:

package pkg;
class A {
    private int i;
}

Result using VisualVm was 20 bytes: enter image description here

But result using JOL was 16 bytes:

pkg.A object internals:
 OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
      0    12        (object header)                           N/A
     12     4    int A.i                                       N/A
Instance size: 16 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

Here is complete code I was using for this test:

package pkg;

import org.openjdk.jol.info.ClassLayout;

import static java.lang.System.out;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        A a = new A();
        out.println(ClassLayout.parseClass(A.class).toPrintable());
    }
}

class A {
    private int i;
}

Have I misuse this tools or misinterpret its results? I was expecting to have same results from both tools.

2

There are 2 best solutions below

0
On BEST ANSWER

You are not going to like it probably... But VisualVM lies, as pretty much explained here (there is a much more in depth video from the same great Shipilev, but I can't seem to find it)

Trust JOL, it's correctly showing you the result.

1
On

Because you are using ClassLayout.parseClass(A.class).

If you want to measure memory utilization of a (instance of A), try

ClassLayout.parseInstance(a).toPrintable()