0

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!

Taras Fityo
  • 77
  • 1
  • 10
  • @Lino i don't need hashcode here, i just need to caclulate how much space object occupies, java has no size of, so i am looking how can i achieve the same result. – Taras Fityo Mar 25 '20 at 11:23
  • Please have a look at this other question: https://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object. Generally the size of an object can vary, depending on the fields you add etc. – Lino Mar 25 '20 at 11:24
  • @Lino, i understand :) But my question is, why the object size is not increasing when i add new fields. – Taras Fityo Mar 25 '20 at 11:30
  • Have you recompiled the class files? Maybe you're working with outdated classes, which would explain this behaviour – Lino Mar 25 '20 at 11:34
  • @Lino i thought the same, but intellij compiles code every time before start.Size is increasing, but only when there is odd number of fields. So it seems strange to me. – Taras Fityo Mar 25 '20 at 11:37
  • @Lino When class has 3 fields it's size is 24.When it has 1-2 fields size is 16.Even if fields are of different types. – Taras Fityo Mar 25 '20 at 11:38
  • 1
    This is expected. Object size is a multiple of 8 bytes for performance. If the size required for fields doesn't sum to a multiple of 8, padding is added. – Joni Mar 25 '20 at 11:46

0 Answers0