简体   繁体   中英

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: 在此处输入图片说明

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.

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.

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

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