Vladimir Kishlaly
Vladimir Kishlaly

Reputation: 1942

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?

Upvotes: 3

Views: 1003

Answers (1)

techPackets
techPackets

Reputation: 4516

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.

Upvotes: 3

Related Questions