I have two different class with static variables. One class with static reference type variables and another class with static primitive type variables. When i calculated the size of the each static variables using Instrumentation.getObjectSize() method it returns the same size. But from my understanding, class object has header section and padding section additional to its global variables so this reference type is always should be great in memory while compared to primitive type. Please find my code below:
ObjectSizeFetcher.java
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
DaysOfWeek1.java
public class DaysOfWeek1 {
public static final DaysOfWeek1 Sunday = new DaysOfWeek1(1);
public static final DaysOfWeek1 Monday = new DaysOfWeek1(2);
public static final DaysOfWeek1 Tuesday = new DaysOfWeek1(4);
public static final DaysOfWeek1 Wednesday = new DaysOfWeek1(8);
public static final DaysOfWeek1 Thursday = new DaysOfWeek1(16);
public static final DaysOfWeek1 Friday = new DaysOfWeek1(32);
public static final DaysOfWeek1 Saturday = new DaysOfWeek1(64);
private int intValue;
private DaysOfWeek(int value) {
intValue = value;
}
}
DaysOfWeek2.java
public final class DaysOfWeek2 {
public static final int Sunday = (1);
public static final int Monday = (2);
public static final int Tuesday = (4);
public static final int Wednesday = (8);
public static final int Thursday = (16);
public static final int Friday = (32);
public static final int Saturday = (64);
}
Test.java
public class Test {
public static void main(String[] args) throws Exception {
int i=10;
long value = ObjectSizeFetcher.getObjectSize(DaysOfWeek1.Friday);
System.out.println(value);// provide 16 bytes
long value1 = ObjectSizeFetcher.getObjectSize(DaysOfWeek2.Sunday);
System.out.println(value1);// provide 16 bytes
long value2 = ObjectSizeFetcher.getObjectSize(i);
System.out.println(value2);// provide 16 bytes
}
}
Can anyone explain me how JVM allocates memory for the above scenario?
Thanks in advance.
Regards, Sarath
getObjectSize()
is meant to give an approximation of the size of objects of the specified type. They aren't affected by static fields, because static fields exist on a per-type basis rather than a per-object basis.
Add as many static fields as you like, and I wouldn't expect getObjectSize
to change.
See more on this question at Stackoverflow