VJS
VJS

Reputation: 2951

java.lang.instrument.Instrumentation is not giving expected result

I am using java.lang.instrument package to get the memory size of java object (can be nested ).

I am using below to get Object Size :

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);
    }
}

I have Person class having below fields :

private String name ; 

private int age;

private Addresses addresses [] ; 

Now need size of below person Object :

    Person person = new Person();
    person.setName("aa");
    person.setAge(11);

    Addresses addresses [] = new Addresses[2000];

    for(int i = 0 ; i < 1000 ; i ++){
        addresses[i] = new Addresses();

        addresses[i].setAddress1("dadadadafasfasf"+i);
        addresses[i].setAddress2("dadadadafasfasfdasdsadsd"+i);
    }

    person.setAddresses(addresses);
    System.out.println("size : " + ObjectSizeFetcher.getObjectSize(person));

Now after executing this, I am getting output as :

size : 24

Issue is If i am iterating this loop 10 times, or 1000 times, or 100000 times, i am getting Size as 24.

I am expected that person object memory size should increase if number of times loop increased as person object is having more addresses.

Why java.lang.instrument.Instrumentation is not giving correct results ?

Upvotes: 1

Views: 585

Answers (2)

arkantos
arkantos

Reputation: 567

Arrays are objects itself and you're declaring only one array.

Addresses addresses [] = new Addresses[2000]; //the single array instance

for(int i = 0 ; i < 1000 ; i ++){
    addresses[i] = new Addresses();

    addresses[i].setAddress1("dadadadafasfasf"+i);
    addresses[i].setAddress2("dadadadafasfasfdasdsadsd"+i);
}

and populate it with address records. So your arrray pointing the same area in memory, it is still the same reference. The only difference made is that you're createing new Addresses instances and fill your memory outside the class in which array addresses[] declared. For further explanation;

Before: addresses[] ----> 0x0000f -> {}

After: addresses[] ----> 0x0000f ->{address1, address2, ..., address1000}

So your reference for addresses[] stays the same, it keeps pointing the same area. It's only the reference and not the array itself.

Upvotes: 0

Maarten Bodewes
Maarten Bodewes

Reputation: 93958

Simply said: an object consist of it's own fields. But if these fields are objects themselves, they consist simply of the reference to those other objects. So your array is an object, and only the reference to that array is included. The size doesn't contain the whole object tree of what an object exists of, in other words.

Upvotes: 1

Related Questions