Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object layout and static fields

The JOL tool gives ability to count object's memory layout.

I've noticed, that static fields do not participate in calculating, for example:

public class Foo {

    private static final int i = 1;

    private char value;

    public Foo(char value) {
        this.value = value;
    }
}

then,

System.out.println(ClassLayout.parseClass(Foo.class).toPrintable());

gives the following output:

com.kishlaly.Foo object internals:
 OFFSET  SIZE  TYPE DESCRIPTION                    VALUE
      0    12       (object header)                N/A
     12     2  char Foo.value                      N/A
     14     2       (loss due to the next object alignment)
Instance size: 16 bytes (estimated, the sample instance is not available)
Space losses: 0 bytes internal + 2 bytes external = 2 bytes total

Where does private static final int lies in memory?

like image 867
Vladimir Kishlaly Avatar asked Nov 27 '25 23:11

Vladimir Kishlaly


1 Answers

The tool is giving the memory layout of an object on the heap. The static content is in the PermGen section of the memory & it's on the JVM implementation whether it is included in the heap or not.

Your tool provided the memory layout of the object, whereas static variable is a class level variable it will be always in the permanent generation section of memory & would not be included in this layout.

like image 81
underdog Avatar answered Nov 30 '25 12:11

underdog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!