I have doubt in memory allocation for int and Integer variable in Java. For measuring memory i have used Instrumentation.getObjectSize() and it produces the same size for both the variables. 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);
}
}
Test.java
public class Test {
public static void main(String[] args) throws Exception {
int i=0;
Integer i1 = new Integer(0);
long value = ObjectSizeFetcher.getObjectSize(i);
System.out.println(value);//prints 16
long value1 = ObjectSizeFetcher.getObjectSize(i1);
System.out.println(value1);//prints 16
}
}
In the above case both the variable size prints the same. My doubt is, int is primitive type and it size 4 bytes and Integer is reference type and its size is 16 bytes but in this case why produces 16 bytes for both the values? If both the take same amount of memory in heap means, it leads to memory issue in java right?
i
gets auto-boxed to an Integer
when passed to getObjectSize
.
So you get the value of the size of promoted variable, not the original primitive int
.
To circumvent this behaviour, build overloads of getObjectSize
for the primitive cases:
public static long getObjectSize(int o) {
return Integer.SIZE / 8;
}
and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With