Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service holds 50 million small entries in a HashMap<Long, Integer> and uses 4 GB of heap. How would you reduce memory, and what would you consider before switching implementation?

Each of the 50 million entries costs about 77 bytes: a 32-byte HashMap node, a 24-byte Long, a 16-byte Integer and a share of the bucket array, so 12 bytes of real data take almost 4 GB. Primitive collections such as fastutil's Long2IntOpenHashMap or Eclipse Collections' LongIntHashMap store the longs and ints in plain arrays and cut this to under 1 GB, and sorted parallel arrays with binary search need only 600 MB for read-mostly data. Before switching, we should measure with a heap histogram, check whether the data belongs in a database or off-heap store, and confirm which Map features the code relies on.

Why this question is asked

Memory problems in Java services often come from the gap between the data we think we store and the objects the JVM actually keeps. A map of numbers looks tiny on paper, yet boxing and per-entry objects multiply its size several times, and the extra heap shows up as longer garbage collection pauses and bigger, more expensive instances. Interviewers ask this to see whether we can do the arithmetic, know the tools that remove the overhead, and still think before replacing a standard class. In this answer, we will measure where the 4 GB goes, look at primitive maps, consider sorted arrays, ask whether the data belongs on the heap at all, and decide what to check before switching.

1Where the 4 GB Goes

A HashMap<Long, Integer> cannot store a long and an int directly, because Java generics work only with objects. Every key becomes a Long object and every value an Integer object, and each pair lives in a HashMap.Node that also holds the hash and a pointer to the next node in its bucket. On a 64-bit JVM with compressed references, the default for heaps under about 32 GB, the sizes add up like this.

Approximate cost of one entry (compressed references)
PartBytesWhat it holds
HashMap.Node3212-byte header, hash, key, value and next pointers, padding
Long key2412-byte header, 8-byte long, padding
Integer value1612-byte header, 4-byte int
Share of the bucket arrayabout 52^26 slots of 4 bytes, spread over 50M entries
Total per entryabout 77times 50 million = about 3.85 GB
Actual data12times 50 million = 600 MB
Exact sizes depend on the JVM and its flags; a heap histogram gives the real numbers.

The bucket array also needs space. To hold 50 million entries with the default load factor of 0.75, the table needs at least 66.7 million slots, so it grows to 2 to the power 26, which is 67 million slots of 4 bytes, about 256 MB, or roughly 5 bytes per entry. Adding it all up gives about 77 bytes per entry and 3.85 GB in total, which matches the 4 GB we see. The actual data is a long and an int, 12 bytes, so the map spends more than 80 percent of its memory on object headers, pointers and padding. Small Integer values from -128 to 127 are cached and shared, which saves a little if many values are small, but the Long keys are almost all distinct objects.

2First, Measure

Before changing anything, we confirm the estimate on the real service. A class histogram of the live heap lists the number of objects and bytes for each class, and it tells us directly whether HashMap$Node, Long and Integer are the top consumers.

Shell
$ jcmd <pid> GC.class_histogram | head -6
num #instances #bytes class name
1: 50000000 1600000000 java.util.HashMap$Node
2: 50012345 1200296280 java.lang.Long
3: 49990012 799840192 java.lang.Integer
4: 1 268435472 [Ljava.util.HashMap$Node;
...

Notice that the numbers line up with our arithmetic: 32 bytes per node, 24 per Long, 16 per Integer, and one bucket array of about 268 MB. The histogram triggers a full collection, so in production we run it on one instance at a quiet time, and we keep the output to compare after the change.

3Option 1: A Primitive Map

Libraries such as fastutil and Eclipse Collections provide maps specialised for primitive types. Long2IntOpenHashMap stores its keys in a long[] and its values in an int[], and resolves collisions by open addressing, probing the next slots in the same arrays instead of chaining nodes. There are no node objects and no boxed numbers.

Java
// fastutil
Long2IntOpenHashMap counts = new Long2IntOpenHashMap(50_000_000);
counts.defaultReturnValue(-1); // what get returns for a missing key
counts.put(42L, 7);
counts.get(42L); // 7, no boxing
counts.get(99L); // -1
counts.addTo(42L, 1); // 8
// Memory: about 2^26 slots x (8 + 4) bytes = about 800 MB instead of about 3.85 GB

This change alone reduces the map to about a fifth of its size, and it usually makes lookups faster too, because the data is in two dense arrays instead of scattered across 150 million objects. The garbage collector also benefits: marking two large arrays is far cheaper than tracing 150 million small objects. The catch is the API. A primitive map uses methods like get(long) and a default return value instead of null, so code that relied on null for a missing key must change.

4Option 2: Sorted Arrays for Read-Mostly Data

If the map is loaded once, for example from a nightly file, and then only read, we can do even better. We sort the keys, keep them in a long[] with the values at the same positions in an int[], and find a key with binary search.

Java
long[] keys = ...; // sorted ascending, 50M entries = 400 MB
int[] values = ...; // values[i] belongs to keys[i] = 200 MB
int lookup(long key) {
int i = Arrays.binarySearch(keys, key);
return i >= 0 ? values[i] : -1; // about 26 comparisons for 50M keys
}

This uses exactly 12 bytes per entry, 600 MB in total, with no wasted slots. The price is that a lookup takes about 26 steps instead of one or two, which is still well under a microsecond, and that adding a key means rebuilding or merging the arrays. For data that changes rarely, it is often the best trade.

5Should the Data Be on the Heap at All?

Fifty million entries is a lot of state for one service instance. Before optimising the in-memory structure, we should ask why it is there. If every instance loads the same data at start-up, it may belong in a database with an index or a shared cache such as Redis, and the service keeps only a small, hot subset. If it must stay local for latency, an off-heap store such as Chronicle Map or a memory-mapped file keeps it outside the garbage-collected heap, so it does not slow collections and can even be shared between processes.

6What to Check Before Switching

We check what the code expects from the map. Does any code iterate it and depend on the order? A primitive open-addressing map has its own unspecified order. Does it rely on null meaning absent, or store null values? Is it shared between threads? The fastutil and Eclipse Collections maps are not thread-safe, just like HashMap. Is the map passed to other code as a java.util.Map? The libraries offer Map adapters, but using them boxes again on every call and loses most of the gain.

Then we measure again, with the same histogram and with the service's latency and GC metrics, so the change is justified by numbers rather than estimates. A typical result is a heap that shrinks from 6 GB to 3 GB, shorter GC pauses, and the possibility of smaller instances.

7Follow-up questions

Would turning off compressed references explain the size?

It would make it worse. Without compressed references, as on heaps over about 32 GB, each pointer takes 8 bytes and object headers grow, so the same map would need well over 5 GB. Keeping the heap under the compressed-references limit is itself a reason to shrink large maps.

Is fastutil or Eclipse Collections better?

Both are mature. fastutil is focused on primitive collections and has very many specialised types; Eclipse Collections also offers a rich API for object collections. I would pick one for the whole company, to avoid two similar dependencies, and measure on our own data.

8Conclusion

In this answer, we saw that a HashMap<Long, Integer> spends about 77 bytes per entry on nodes, boxed numbers and the bucket array, which is why 50 million entries fill 4 GB. Primitive maps store the numbers in arrays and cut this to about 800 MB, sorted arrays with binary search reach the minimum 600 MB for read-mostly data, and a database or off-heap store may be the better home for data this large. Whatever we choose, we measure with a heap histogram before and after and check the Map features the code relies on.

What to say in the interviewAbout 90 seconds aloud

Open with

First I would explain why it is so big. A HashMap of Long to Integer boxes every key and value, so each entry is a 32-byte node, a 24-byte Long and a 16-byte Integer, plus about 5 bytes of bucket array, roughly 77 bytes for 12 bytes of real data.

Then, if they want more

Times 50 million, that is close to 4 GB. I would confirm it with jcmd GC.class_histogram and keep that output as the baseline. Then I would look at the options. The usual fix is a primitive map, like fastutil's Long2IntOpenHashMap or Eclipse Collections' LongIntHashMap, which keeps keys in a long array and values in an int array with open addressing.

That is around 800 MB, often faster, and much easier on the GC because there are no millions of small objects. If the data is read-mostly, sorted parallel arrays with binary search get it to 600 MB, at the cost of about 26 comparisons per lookup and rebuilding on change.

I would also ask whether this data belongs in each instance at all, or in a database, a shared cache, or an off-heap store. Before switching, I check what the code relies on: iteration order, null for missing keys, thread safety, and whether the map is passed around as java.util.Map, since adapters would box again. Then I measure heap, GC pauses and latency after the change.

About this answer

Last updated
12 November 2026
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 holds 50 million small entries in a HashMap<Long, Integer> and uses 4 GB of...": https://scrivio-interview-library.netlify.app/java/collections-overview/d5082f237f/