2

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.

Artem Petrov
  • 662
  • 4
  • 12

2 Answers2

1

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.

Eugene
  • 102,901
  • 10
  • 149
  • 252
0

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()
rkosegi
  • 12,129
  • 5
  • 46
  • 75
  • I've changed the test to use `ClassLayout.parseInstance(a)` but size of the object is still 16 bytes acording to JOL – Artem Petrov Oct 22 '17 at 12:10