Video in progress

A service holds a Map<Long, Long> with several million entries keyed by ID, and half the heap is wrapper objects. How do you reduce the memory?

Each Long key and value is a separate 24-byte object, on top of a 32-byte HashMap.Node and the table reference. So one 16-byte pair becomes about 85 bytes. Primitive collections (fastutil, Eclipse Collections, HPPC) or sorted long[] arrays take several times less space and put almost no load on the GC.

📖 Answer

The arithmetic (with compressed oops):

  • HashMap.Node: header 12 + hash 4 + key/value/next references 12 → 32 bytes;
  • a Long key: 24 bytes, a Long value: 24 bytes;
  • the reference in the table: 4 bytes, about 5-6 bytes with a load factor of 0.75.

About 85 bytes in total. 10 million entries make 850 MB, while the useful data is 160 MB. On top of that, 30 million objects, each of which is separate work for GC marking.

The options:

// fastutil: open addressing, two long[] arrays
Long2LongOpenHashMap map = new Long2LongOpenHashMap(10_000_000);
map.put(userId, balance);
long v = map.get(userId);   // no boxing

Here memory is about 16 bytes / load factor ≈ 22-25 bytes per entry, in just two big arrays, which are almost invisible to the GC.

Other ways:

  • if the data rarely changes: sorted long[] keys + long[] values and Arrays.binarySearch. The most compact, reads are O(log n);
  • if the value is an object with many fields: "struct of arrays", a separate primitive array for each field;
  • a very big, rarely changing set: off-heap (Chronicle Map, FFM MemorySegment) or an external cache.

The trade-offs: a third-party dependency (the fastutil jar is big, but split into modules), the API isn't the standard Map, so you have to convert at the edge of your code, and there is no null value (you have to work with a default value). That is why I do this only when a profile or heap histogram shows that wrappers really are at the top.

To verify: GC.class_histogram and the "Old after GC" size before and after the change, with the same data. Often halving the pod's memory and noticeably shortening GC pauses comes from this one change.