javavisualvmjol

Why VisualVm and JOL tools give different results for object size


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.


Solution

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