Video in progress

A HashMap<Long, Long> with tens of millions of entries takes up a large part of the heap in your service. How do you analyze it and cut the memory?

First I measure where the memory is going with a heap histogram or a dump: usually the bulk is Node objects and boxed Longs. Then moving to a primitive collection (fastutil, Eclipse Collections) or changing the data structure saves 4 to 6 times.

📖 Answer

Do the math. On a 64-bit JVM with compressed oops, one entry takes roughly:

  • HashMap$Node: 32 bytes (header + hash + key + value + next);
  • key Long: 16 bytes, value Long: 16 bytes;
  • a slot in the table: 4 bytes, more with the load factor.

So one pair is about 70 bytes, while the useful data is 16 bytes. 20 million entries is around 1.4 GB.

I start the analysis like this:

jcmd <pid> GC.class_histogram | head -20
# or a full dump and the dominator tree in MAT
jcmd <pid> GC.heap_dump /tmp/app.hprof

If HashMap$Node and java.lang.Long are at the top of the histogram, the diagnosis is clear.

The options, cheapest first:

  1. A primitive map: Long2LongOpenHashMap (fastutil) or Eclipse's LongLongHashMap. Open addressing, two long[] arrays, about 20–25 bytes per pair. Often that is enough.
  2. If the data doesn't change, two sorted long[] arrays and Arrays.binarySearch. 16 bytes per pair, lookup is O(log n).
  3. Does everything have to be in memory? Sometimes 5% of the entries serve 95% of the requests, and a bounded cache plus the DB is enough.
  4. At very large volumes, off-heap (Chronicle Map) or an embedded store (RocksDB). That eases the GC, but adds serialization cost and operational complexity.

After any change I check read speed with JMH or a load test. Saving memory doesn't mean latency didn't get worse.