Suri
Suri

Reputation: 209

Calculate the memory usage of a HashMap in java

I want to calculate the memory usage of two HashMaps in Java and I did these two methods.

1) I use the visualVM and I got following result.

Is it just the size of the Hashmap's pointer not the real amount of memory usage with this Hashmap?

Because, it just used ''67283648'' bytes. enter image description here

2) I run the following code which fill two HashMaps and I got ''576132056'' bytes as a result.

    Runtime runtime = Runtime.getRuntime();
    long memory = runtime.totalMemory()- runtime.freeMemory();
    HashMap<String, TypePosting> typeInvIndex=qpu.loadInvTypeIndex();
    HashMap<Integer,String> map=qpu.loadMapTypeEntityId();
    long memory1 = runtime.totalMemory()- runtime.freeMemory();
    System.out.println(memory1- memory);

I just asked this question to be sure that I the second result is the correct value of space usage of these two Hashmaps correctly. Am I correct?

Upvotes: 3

Views: 6177

Answers (2)

plastique
plastique

Reputation: 1204

Please see the In Java, what is the best way to determine the size of an object?. There is a short and nice example of how to measure any java object size.

Upvotes: 2

Cootri
Cootri

Reputation: 3836

IMHO the best (precise and easy to implement) way to find java object instance memory footprint at runtime is to use Instrumentation interface and implement simple java agent.

It is a common practice, there are plenty of how-tos and code samples in the Web. Just one example (which you can use as a starting point)

Upvotes: 2

Related Questions