i created Java Agent to calculate object size
public class InstrumentationAgent
{
private static Instrumentation mInstrumentation;
public static void premain(final String agentArgs, final Instrumentation inst)
{
mInstrumentation = inst;
}
public static long getObjectSize(final Object object)
{
if (mInstrumentation == null) {
throw new IllegalStateException("Agent not initialized.");
}
return mInstrumentation.getObjectSize(object);
}
So it returns memory size that object occupies, but i noticed that when i add new fields to test object it sometimes returns the same amount of memory
public class TestObject
{
private String firstInt= 1;
private String secondInt = 2;
public static void main(String[] args)
{
System.out.println(InstrumentationAgent.getObjectSize(new TestObject()));
}
}
It outputs 16. When i remove 'secondInt' from my test class it still outputs 16. It seems like when i add two new fields the size is bigger, but it stays the same if i add one field, why is it so? Thanks!