Java Object Layout and Static Fields
The JOL tool provides the ability to calculate the memory layout of an object.
I noticed that static fields are not involved in the calculation, 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 the private static final int lie in memory?
+3
source to share
1 answer
The tool gives the memory layout of the object on the heap. Static content is in the PermGen section in memory and in the JVM implementation it is heaped or not.
Your tool provided an object memory mock, whereas a static variable is a class level variable, it will always be in the persistent memory generation section and will not be included in that mock.
+2
source to share