3

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?

Suri
  • 209
  • 1
  • 4
  • 10
  • 3
    I would under no circumstances trust #2 as a measurement technique. – Louis Wasserman Mar 29 '16 at 19:12
  • 1
    And as far as #1 goes, that's the number of bytes directly taken by node objects in the hash maps, which does not account for the full memory consumption of `HashMap`s generally. – Louis Wasserman Mar 29 '16 at 19:13
  • Louis, I am just curious, which methods of getting runtime instances footprint do you use in Google? Or how YOU will solve this problem? Thanks in advance – Cootri Mar 29 '16 at 19:42

2 Answers2

2

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)

Cootri
  • 3,806
  • 20
  • 30
2

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.

Community
  • 1
  • 1
plastique
  • 1,164
  • 2
  • 9
  • 19