NIVESH SENGAR
NIVESH SENGAR

Reputation: 1333

Getting Map size on memory(RAM)

I am using a HashMap to cache some important data when my application starts.
This cache sometime grows and then reduced. I want to know how much memory it is taking on RAM.
Is it possible to get memory taken by a map in KB? Is there any API?

Upvotes: 10

Views: 23227

Answers (5)

marcolopes
marcolopes

Reputation: 9288

i'm using this method to estimate the MAP size:

public static void size(Map map) {
    try{
        System.out.println("Index Size: " + map.size());
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        ObjectOutputStream oos=new ObjectOutputStream(baos);
        oos.writeObject(map);
        oos.close();
        System.out.println("Data Size: " + baos.size());
    }catch(IOException e){
        e.printStackTrace();
    }
}

Upvotes: 15

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

It depends very much on your JVM vendor and version. You can have a look at this presentation for a rough estimation.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382474

It's virtually impossible to compute the real size of an object without instrumentation.

Sometimes you can compute it given the size of pointers, primitive types, the overhead of objects, etc. but doing it for something as complex as a HashMap with content (the real size size is dependent of its history and hash factor and the hascode of all its elements modulo the hash factor) is near impossible.

The only real solution is to use a heap analyzer, such as Eclipse Mat.

Upvotes: 3

duffymo
duffymo

Reputation: 309018

You realize, of course, that your Map holds references to objects that live out on the heap, not the objects themselves. So it's meaningless to ask how much memory the Map is consuming without chasing down the entire reference tree to add up the bytes for the keys and the values.

The object doesn't do it; there's no way to accomplish it.

Like the wise comment above said, get Visual VM with all the plugins and profile your app.

Upvotes: 4

Valchev
Valchev

Reputation: 1530

There is a good tool for this purpose: ClassMexer

You can estimate the memory of the HashMap, including referenced objects by:

long noBytes = MemoryUtil.deepMemoryUsageOf(myCacheMap);

Upvotes: 7

Related Questions