Quick revision
The short answer
A default HashMap filled with 30 million entries resizes about 22 times on the way, and every resize allocates a table twice as large while the old one is still alive, so loading wastes time moving entries and pushes peak heap far above the final size. I would pre-size the map with HashMap.newHashMap(n) so no resize happens, consider a more compact structure such as sorted primitive arrays or a primitive-keyed map built once and published immutably, and ask whether all twelve services really need a full in-heap copy or could share one store. Each change should be measured for startup time and heap before it is rolled out.
What to remember
In this answer, we saw that loading 30 million entries into a default HashMap causes about 22 resizes, each allocating a larger table while the old one is still live, which slows start-up and pushes peak heap up, especially when rows are first collected into a list. Pre-sizing with HashMap.newHashMap(n) and streaming the rows removes most of that cheaply. A compact structure such as sorted primitive arrays or a primitive-keyed map, built once and published immutably, cuts the steady-state memory, and a shared store or off-heap map can remove the twelve copies at the cost of lookup latency and operations. Every step should be measured for start-up time and heap before it is rolled out.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A default HashMap filled with 30 million entries resizes about 22 times on the way, and every resize allocates a table twice as large while the old one is still alive, so loading wastes time moving entries and pushes peak heap far above the final size. I would pre-size the map with HashMap.newHashMap(n) so no resize happens, consider a more compact structure such as sorted primitive arrays or a primitive-keyed map built once and published immutably, and ask whether all twelve services really need a full in-heap copy or could share one store. Each change should be measured for startup time and heap before it is rolled out.
Why this question is asked
Reference data maps, such as product catalogues, postcode tables or exchange routes, tend to grow quietly for years until start-up takes minutes and every service needs a bigger heap. This scenario is about more than HashMap internals: it asks us to fix a cost multiplied across twelve services and to judge when an in-process map stops being the right design. Interviewers ask it at a senior level to see whether we can estimate memory with real numbers, choose between cheap fixes and structural ones, and weigh their operational cost. In this answer, we will recap how a HashMap grows, estimate the memory of a 30 million entry map, explain the slow start and the heap spike, and then go through the options in order of cost.
1A Quick Recap: How a HashMap Grows
A HashMap stores its entries in an internal array, the table, whose length is a power of two. When the number of entries passes the threshold, table length times the load factor of 0.75, the map allocates a new table twice as long and moves every entry into it. A default map starts at 16 slots, so reaching 30 million entries takes resizes to 32, 64 and so on up to 2^26 = 67,108,864 slots, which is 22 resizes.
Each resize touches every entry already in the map. Summed over all the doublings, the map moves about as many entries again as it finally holds, around 30 million moves on top of the 30 million inserts.
2Estimating the Memory of One Map
Let us estimate a map from Long keys to small value objects on a 64-bit JVM with compressed references. Each entry is a HashMap.Node of about 32 bytes. Each boxed Long key is 16 bytes. The table of 67 million references is about 256 MB. The value objects come on top, say 32 bytes each for a small record.
| Part | Per entry | Total | Can we avoid it? |
|---|---|---|---|
HashMap.Node | 32 B | about 960 MB | yes, with open addressing or arrays |
| Boxed Long key | 16 B | about 480 MB | yes, with primitive keys |
| Table slots | about 9 B | about 256 MB | partly, with a denser layout |
| Value object | 32 B | about 960 MB | only by storing fewer fields |
Notice that more than half of the memory is overhead, Nodes, boxed keys and the table, rather than the data itself. That observation drives the more structural options later.
3Why Start-Up Is Slow and the Heap Spikes
Three things happen during loading. First, the 22 resizes move tens of millions of entries, each move touching memory that is not in the CPU cache. Second, during the last resize the old table of 128 MB and the new one of 256 MB are both alive, while millions of Nodes and keys are being created. Third, the garbage collector has to copy tens of millions of new objects from the young generation into the old generation, which on its own can take many seconds of pause or concurrent work.
If the loader first reads all rows into a List and then puts them into the map, the parsed rows and the map are both alive at the peak, which is the usual reason heap use almost doubles. All of this is temporary, but the heap must be sized for the peak, so every service carries the cost for its whole life.
- Read rows from the sourceoften parsed into a temporary List first
- put() each rowNode and boxed key allocated per entry
- Size passes threshold?happens 22 timesYesAllocate table twice as large, move all entriesNoNext row
- Old and new tables alive togetherpeak heap during the last resizes
- GC promotes tens of millions of objectslong pauses or heavy concurrent work
5 steps in order. Play them, or step through them one at a time.
4Option 1: Pre-Size the Map
The cheapest fix is a one-line change. If we know the number of entries, which we usually do from the source, we create the map at its final size. HashMap.newHashMap(int numMappings), added in Java 19, computes the capacity for the default load factor, so no resize happens. On older JDKs the equivalent is new HashMap<>((int) Math.ceil(n / 0.75)).
Streaming the rows instead of collecting them first removes the second copy at the peak. Together these changes typically cut loading time noticeably and remove most of the spike, without touching any caller. They do not reduce the steady-state 2.6 GB.
5Option 2: A More Compact Structure
Since data is loaded once and then only read, we can pick a structure built for that. If keys are longs, a sorted long[] of keys with a parallel array of values gives lookups by Arrays.binarySearch in about 25 steps for 30 million entries, with no Node and no boxed key: 240 MB for the keys instead of about 1.5 GB of Nodes and Longs. A primitive-keyed open-addressing map, for example from fastutil, Eclipse Collections or HPPC, keeps O(1) lookups and also removes Nodes and boxing. If the values are small, they can be stored in primitive arrays too.
Whatever we build, we build it fully in a local variable and then publish it in one step, through a final field set in the constructor or a volatile reference, wrapped in an immutable or read-only API. Readers then never see a half-built structure, and a reload can build the next version beside the current one and swap it.
6Option 3: Question the Twelve Copies
Twelve full copies of 2.6 GB is about 31 GB of heap, twelve slow start-ups and twelve loaders to keep correct. The real question is whether every service needs every entry, at in-heap speed.
A shared store such as Redis or a database with a good index gives one copy, but each lookup becomes a network call of a few hundred microseconds or more, and the store is a new dependency that can fail. An off-heap, memory-mapped map on each host, built once and shared by the processes on that host, keeps lookups in the microsecond range and moves the data out of the garbage-collected heap, at the cost of a more specialised library and operational knowledge. A smaller option is to give each service only the slice it uses, if most services need only a region or a product line. Which is right depends on the lookup rate and the latency budget: a service doing millions of lookups per second needs local data, while one doing a few hundred can afford a remote call and a small local cache.
7Measuring Before Rolling Out
Before changing twelve services, I would measure one. The baseline is start-up time to ready, peak and steady-state heap from GC logs (-Xlog:gc), and lookup latency under load. Then I would apply pre-sizing and streaming first, because they are safe and cheap, measure again, and only then evaluate a compact structure or a shared store, with a JMH benchmark for lookups and a load test for the whole service. Publishing the numbers, for example start-up from minutes to tens of seconds and heap from 6 GB to 3.5 GB per instance, is what convinces the other eleven teams.
8Follow-up questions
Would a ConcurrentHashMap help here?
Not for this problem. The data is loaded once and then read, so there is no need for concurrent writes. ConcurrentHashMap has similar per-entry overhead and is no faster to load. Building a structure privately and publishing it immutably gives thread-safe reads without any locking.
Could we speed up loading by building the map in parallel?
HashMap cannot be filled by several threads at once. We could parse rows in parallel and insert in one thread, or build a sorted array in parallel with Arrays.parallelSort, which suits the compact array option well. Often a faster input format, such as a binary snapshot instead of CSV or JSON, helps more than parallelism.
Does a bigger heap or a different GC solve it?
It hides it. A bigger heap absorbs the spike and a different collector may shorten pauses, but the waste is still paid in every one of the twelve services and in start-up time. Removing the resizes and the per-entry overhead fixes the cause.
9Conclusion
In this answer, we saw that loading 30 million entries into a default HashMap causes about 22 resizes, each allocating a larger table while the old one is still live, which slows start-up and pushes peak heap up, especially when rows are first collected into a list. Pre-sizing with HashMap.newHashMap(n) and streaming the rows removes most of that cheaply. A compact structure such as sorted primitive arrays or a primitive-keyed map, built once and published immutably, cuts the steady-state memory, and a shared store or off-heap map can remove the twelve copies at the cost of lookup latency and operations. Every step should be measured for start-up time and heap before it is rolled out.
Open with
First I would explain where the time and memory go. A default HashMap starts at 16 slots, so reaching 30 million entries means about 22 resizes, and each one allocates a table twice as large and moves every entry while the old table is still alive.
Then, if they want more
On top of that, loaders often parse everything into a list first, so the rows and the map exist together at the peak, which is why heap almost doubles.
Per entry, a map of Long keys costs about 32 bytes of Node plus 16 bytes of boxed key, so one map is around 2.5 gigabytes, and twelve services hold about 30.
My first recommendation is cheap and safe: pre-size with HashMap.newHashMap(n), which is Java 19 and later, or the n over 0.75 formula on older JDKs, and stream the rows into the map instead of collecting them. That removes all resizes and most of the spike.
Second, because the data is read-only after loading, I would consider a compact structure, such as sorted long arrays with binary search, or a primitive-keyed open-addressing map, built once and published immutably through a final or volatile field. That can cut memory by half or more. Third, I would ask whether all twelve services need the full data in heap.
A shared store or an off-heap memory-mapped map gives one copy but adds lookup latency and an operational dependency, so it depends on lookup rates. I would measure start-up time and heap on one service before and after each change, then roll out with the numbers.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 19
- 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.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
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 "Twelve services each load a reference-data HashMap of about 30 million entries at...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/9a54f7623b/