Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Map size on memory(RAM)

Tags:

java

memory

map

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?

like image 256
NIVESH SENGAR Avatar asked Jul 04 '12 13:07

NIVESH SENGAR


People also ask

How does HashMap calculate memory size?

Only the reference to the list is stored in the value. In a 32 bits JVM, in one Map entry, you have 4 bytes for the "aby" reference + 4 bytes for the List reference + 4 bytes for the "hashcode" int property of Map entry + 4 bytes for the "next" property of Map entry.

What is default Map size?

The map size is always constant. i.e., 1 . But default size of hash map is 16 bits .

How does Map size work?

Map size() method in Java is used to get the total number entries i.e, key-value pair. So this method is useful when you want total entries present on the map. If the map contains more than Integer. MAX_VALUE elements return Integer.


1 Answers

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();
    }
}
like image 118
marcolopes Avatar answered Oct 11 '22 09:10

marcolopes