Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service keeps a Map<Long, Long> with 50 million entries and it uses roughly 4 GB of heap. Estimate where the memory goes and propose alternatives.

Almost all of the 4 GB is overhead: each entry is a HashMap.Node of about 32 bytes, a boxed Long key and a boxed Long value of about 24 bytes each with default headers, and a share of the bucket array, so roughly 80 to 90 bytes per entry to store 16 bytes of data. A primitive-specialised map that keeps keys and values in long arrays cuts this to around 20 bytes per entry, a plain long[] is smaller still if keys are dense, and off-heap or external stores fit when the data should not live in the GC heap at all.

Background to this question

Capacity questions like this one separate people who use collections from people who understand what they cost. A map of 50 million numbers sounds like 800 MB of data, yet the heap shows 4 GB, and that gap decides instance sizes, GC pause times and sometimes whether the service fits on a machine at all. In this answer, we will recap how a HashMap stores an entry, estimate the bytes per entry step by step, check the estimate against the observed 4 GB, and then compare the alternatives and what each one costs.

1A Quick Recap of How HashMap Stores an Entry

A HashMap holds an array called the table, and each slot of the table is a bucket. Every entry lives in a separate object called a Node, which holds the cached hash, a reference to the key, a reference to the value and a reference to the next node in the same bucket.

The key and the value of a Map<Long, Long> are not numbers but references to Long objects, the wrapper class for a long. So one logical entry, two 8-byte numbers, is spread over three heap objects plus one slot in the table. Every heap object also carries a header, the bookkeeping the JVM needs for locking, hashing and GC, which is 12 bytes with the default compressed class pointers, and objects are aligned to 8 bytes.

2Estimating the Bytes per Entry

Let us add it up for a 64-bit JVM with a heap under 32 GB, so compressed references of 4 bytes are used, and default object headers.

Java
// HashMap.Node: header 12 + int hash 4 + key ref 4 + value ref 4 + next ref 4 = 28 -> 32 bytes
// Long key: header 12 + long 8 = 20 -> 24 bytes
// Long value: header 12 + long 8 = 20 -> 24 bytes
// Table slot: 50,000,000 entries need capacity 2^26 = 67,108,864 slots
// 67,108,864 x 4 bytes = 268 MB, about 5.4 bytes per entry
// Total per entry: 32 + 24 + 24 + 5.4 = about 85 bytes
// 50,000,000 x 85 bytes = about 4.25 GB
Where 85 bytes per entry go (default headers)
PartBytes per entryUseful data
HashMap.Node32none, pure structure
Long key object248
Long value object248
Table slot (load factor 0.75)about 5.4none
Totalabout 8516
Roughly one byte in five is actual data.

That matches the roughly 4 GB the service shows. The real data is 16 bytes per entry, so about 80 percent of the memory is object headers, alignment padding, references and empty table slots. Notice that the boxed key and value alone take 48 bytes, three times the size of the numbers inside them.

Two refinements are worth knowing. With compact object headers, available in JDK 25 as an opt-in with -XX:+UseCompactObjectHeaders, headers shrink to 8 bytes, a Long becomes 16 bytes and a Node 24 bytes, so the total drops to around 60 to 70 bytes per entry. And the memory is not the only cost: 150 million small objects is a lot for the garbage collector to trace and copy, so marking and promotion work grow with the object count, not with the data size.

3Alternative 1: A Primitive-Specialised Map

Libraries such as fastutil, Eclipse Collections, Agrona and HPPC offer maps specialised for primitive keys and values. Instead of nodes and wrapper objects, they use open addressing: keys and values sit directly in long arrays, and a collision is resolved by probing the next slot.

Java
// fastutil
Long2LongOpenHashMap m = new Long2LongOpenHashMap(50_000_000);
m.put(42L, 7L);
long v = m.get(42L); // 7, no boxing
m.defaultReturnValue(-1L); // value returned for a missing key, instead of null
// Memory: two long[] arrays of 2^26 slots each
// 67,108,864 x 16 bytes = about 1.07 GB, about 21 bytes per entry (4x smaller)

The map now consists of a couple of large arrays rather than 150 million objects, so the GC has almost nothing to trace inside it. Lookups are also faster, because the key is in the array itself and probing is cache-friendly. The costs are an extra dependency, an API that differs slightly from java.util.Map (missing keys return a default value rather than null), and a growth step that briefly needs both the old and new arrays.

4Alternative 2: Dense Keys and Plain Arrays

If the keys are dense, for example ids from 0 to 60 million with few gaps, we do not need hashing at all. A long[] indexed by the key holds the value directly.

Java
long[] valueById = new long[60_000_000]; // 480 MB, 8 bytes per possible key
valueById[42] = 7L;
long v = valueById[42]; // 7
// Need to tell "absent" from 0? Use a sentinel such as Long.MIN_VALUE, or a BitSet

Even with some empty slots this is far smaller than any map. A related option for data that is built once and then only read is a pair of sorted long arrays searched with Arrays.binarySearch: 800 MB for 50 million entries, no wasted slots, at the cost of logarithmic lookups and expensive inserts.

5Alternative 3: Moving the Data Out of the Heap

Sometimes the right question is whether this data belongs in the JVM heap at all. If it is large, rarely changes and is shared by several processes, an off-heap map such as Chronicle Map, or memory accessed through the Foreign Function and Memory API, keeps it outside the GC's view. If it is really a lookup service, an external store such as Redis or an embedded RocksDB may be simpler to operate, at the cost of serialisation and, for a remote store, a network hop per lookup.

We choose based on how hot the lookups are. In-heap primitive maps give nanosecond lookups. Off-heap maps add some encoding cost but keep the GC heap small. A remote store adds a round trip of hundreds of microseconds but lets many instances share one copy.

6What About Project Valhalla?

Project Valhalla aims to let Java define value classes, objects without identity that the JVM can store flattened inside arrays and fields, and eventually to make generics over primitives practical. That would remove much of the boxing overhead shown above. But value classes are not a final feature in JDK 25; they are available only in early-access builds and preview work, so we cannot plan production memory around them today. Check the status for your target JDK.

Options for 50 million long-to-long entries
OptionApprox. memoryTrade-off
HashMap<Long, Long>about 4.2 GBstandard API, 150M objects for the GC
Primitive open-addressing mapabout 1.1 GBextra library, default value instead of null
long[] indexed by keyabout 0.4 to 0.5 GBonly for dense keys
Sorted long[] pairsabout 0.8 GBread-mostly, log n lookups
Off-heap or external storelittle heapencoding cost or a network hop
Estimates with compressed references and default headers.

7Follow-up questions

Would a TreeMap<Long, Long> be any better?

No, worse. A TreeMap.Entry holds the key, the value, left, right and parent references and a colour flag, which is about 40 bytes, plus the same two boxed Longs. It uses more memory than HashMap and adds logarithmic lookups.

Does setting a lower load factor help memory?

No, the opposite. A lower load factor means more empty table slots. A higher load factor, such as 0.9 in a primitive map, saves memory at the cost of longer probe sequences. With HashMap the table is only about 6 percent of the total anyway; the nodes and boxes dominate.

How would you verify the estimate on the real service?

Take a heap histogram with jcmd <pid> GC.class_histogram and look at the instance counts and bytes for HashMap$Node and java.lang.Long, or open a heap dump in a tool such as Eclipse MAT and check the retained size of the map. JOL can print the exact layout of one Node and one Long on that JVM.

8Conclusion

In this answer, we estimated a HashMap<Long, Long> entry at about 85 bytes with default headers: a 32-byte node, two 24-byte Long objects and about 5 bytes of table, which explains the 4 GB for 50 million entries holding only 800 MB of data. Compact object headers lower that, but the main fix is structural. Primitive maps that store keys and values in long arrays use about a quarter of the memory and remove 150 million objects from GC work, a plain long[] is smaller still for dense keys, and off-heap or external stores fit when the data should leave the heap. Valhalla may help in the future, but it is not a final feature in JDK 25.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start by estimating per entry. With compressed references, each HashMap entry is a Node of about 32 bytes: a 12-byte header, the hash and three references.

Then, if they want more

The key and value are separate Long objects, each a 12-byte header plus 8 bytes, rounded up to 24 bytes. And at a load factor of 0.75, 50 million entries need a table of 2 to the 26 slots, about 268 MB, or 5 bytes per entry.

That is about 85 bytes per entry for 16 bytes of real data, so 50 million entries come to roughly 4.2 GB, which matches what we see. With compact object headers in JDK 25 it drops somewhat, but the structure is still the problem, and the 150 million objects also cost GC time.

The first alternative is a primitive map from fastutil, Eclipse Collections, Agrona or HPPC, which keeps keys and values in long arrays with open addressing: around 1.1 GB, a quarter of the size, and almost nothing for the GC to trace. If the keys are dense, a long array indexed by key is smaller still, around 400 to 500 MB.

If the data is huge, read-mostly or shared, I would consider an off-heap map or an external store. Valhalla's value classes may help eventually, but they are not final in JDK 25.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service keeps a Map<Long, Long> with 50 million entries and it uses roughly 4 GB of...": https://scrivio-interview-library.netlify.app/java/java-performance/e7df28875b/