Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A service keeps a HashSet<Long> of about 10 million user ids in memory and the heap is under pressure. Estimate the cost and propose alternatives.

A HashSet<Long> costs roughly 60 bytes per element with compressed references: a 32-byte HashMap node, a 24-byte boxed Long and a share of the bucket table. So 10 million ids take around 600 MB for data that is only 80 MB as raw longs. Depending on what the service needs, a sorted long[] with binary search, a primitive hash set from a library such as fastutil or Eclipse Collections, a RoaringBitmap or BitSet for dense ids, or a Bloom filter if approximate answers are acceptable can cut that by 5 to 50 times. We confirm the numbers with a heap histogram or JOL before changing anything.

Why this question is asked

Large sets of ids appear in many services: blocklists, entitlements, users already notified, or ids loaded for fast filtering. They work fine at a hundred thousand elements and then quietly dominate the heap at ten million, causing long GC pauses and out-of-memory errors. Interviewers ask this scenario to see whether we can estimate memory from first principles, explain where the overhead comes from, and choose an alternative that fits the access pattern. In this answer, we will estimate the cost of HashSet<Long> step by step, measure it, and then compare the alternatives with numbers and their trade-offs.

1Where the Memory Goes

A HashSet is a HashMap underneath, and every element becomes a map entry. With compressed object pointers, the default on 64-bit JVMs for heaps under about 32 GB, each object has a 12-byte header and references are 4 bytes, and objects are padded to multiples of 8 bytes.

A HashMap.Node holds an int hash and three references, key, value and next: 12 + 4 + 4 + 4 + 4 = 28 bytes, padded to 32. The key is a boxed Long, a full object with a header and an 8-byte long: 12 + 8 = 20, padded to 24. Finally, the bucket table is an array of references. For 10 million entries at the default load factor of 0.75, the table grows to 16,777,216 slots of 4 bytes, about 67 MB, which is about 7 bytes per element. Adding it up gives about 63 bytes per element, and more without compressed references, when the header grows to 16 bytes and references to 8.

Cost of one element in HashSet<Long> (compressed references)
PartSizeWhy
HashMap.Node32 bytesheader 12 + hash 4 + key, value, next 12, padded
Boxed Long24 bytesheader 12 + long 8, padded
Table slot shareabout 7 bytes16.8 million slots x 4 bytes / 10 million
Total per elementabout 63 bytesversus 8 bytes for a raw long
10 million elements: roughly 630 MB instead of 80 MB.

2Measuring Instead of Guessing

The estimate tells us what to look for, but the JVM version, flags and data can change it, so we measure. On a running service, jcmd prints a class histogram, the number of instances and bytes per class.

Shell
$ jcmd 4711 GC.class_histogram | head
num #instances #bytes class name
1: 10000412 320013184 java.util.HashMap$Node
2: 10000950 240022800 java.lang.Long
3: 231 67112960 [Ljava.util.HashMap$Node;

The three lines match the estimate almost exactly: 320 MB of nodes, 240 MB of Longs and 67 MB of table, about 627 MB in all. For a single object graph in a test, JOL, the Java Object Layout tool from OpenJDK, can print the exact layout of a class and the total footprint of a structure, which is how we would compare alternatives before choosing one.

3Alternative 1: A Sorted long[]

If the set is built once, or changes rarely, and we mainly ask contains, the most compact exact structure is a sorted primitive array.

Java
long[] ids = loadIds(); // 10,000,000 ids
Arrays.sort(ids); // about 80 MB in total
boolean contains(long id) {
return Arrays.binarySearch(ids, id) >= 0; // about 24 comparisons
}

Memory drops from about 630 MB to 80 MB, and the GC has one object to trace instead of 20 million. The costs are that contains is O(log n) instead of O(1), still well under a microsecond, and that adding an id means rebuilding or batching, as with any sorted array.

4Alternative 2: A Primitive Collection Library

Libraries such as fastutil and Eclipse Collections offer hash sets of primitive longs, stored in a plain long[] with open addressing, so there are no nodes and no boxing. A LongOpenHashSet for 10 million elements at a 0.75 load factor uses a table of 16,777,216 longs, about 134 MB, and keeps O(1) add, remove and contains.

Java
LongOpenHashSet set = new LongOpenHashSet(10_000_000); // fastutil
set.add(123_456_789L); // no boxing
set.contains(123_456_789L); // true

This is the choice when the set changes often and we need O(1) operations. The trade-off is a dependency and an API that is not java.util.Set<Long> at the boundaries; passing the set to code that expects Set<Long> boxes the values again.

5Alternative 3: Bitmaps and Bloom Filters

If ids are dense, for example users numbered from 1 to 50 million, a bit per possible id is enough. A java.util.BitSet over 50 million ids uses about 6 MB, regardless of how many are set. When ids are clustered but not dense, a RoaringBitmap compresses runs and sparse regions and is widely used for exactly this kind of id set; for ids beyond the int range it has a 64-bit variant. Both give very fast membership tests and set operations such as intersection.

If the service can tolerate occasional false positives, for example as a quick pre-check before a database lookup, a Bloom filter is far smaller still. At a 1% false positive rate it needs about 9.6 bits per element, roughly 12 MB for 10 million ids, and it never gives a false negative. It cannot list its elements or remove them, so it suits filters, not sources of truth.

Options for 10 million ids
StructureApprox. memorycontainsNotes
HashSet<Long>630 MBO(1)boxing, 20 million objects for the GC
Sorted long[]80 MBO(log n)rebuild or batch to add
fastutil LongOpenHashSet134 MBO(1)extra dependency, non-JDK API
BitSet (ids 1 to 50 million)6 MBO(1)only for dense ids
Bloom filter, 1% error12 MBO(k)false positives, no removal
Figures are rough and depend on data; measure with JOL or a heap histogram.

6Follow-up questions

Why does the number of objects matter, not just the bytes?

The garbage collector must trace live objects. Twenty million small objects take far longer to mark and, in some collectors, to copy than one large array of the same total size. Moving to a primitive array can shorten GC pauses as much as it reduces heap use.

Would setting the HashSet's initial capacity help?

It avoids the cost of resizing during loading and can avoid an oversized table, but the dominant cost is the 56 bytes of node and Long per element, which no capacity setting changes. Capacity tuning is a small win compared with removing the boxing.

How would you choose between these options?

By the access pattern and correctness needs. If the set rarely changes, the sorted array is simplest. If it changes often, a primitive hash set. If ids are dense or clustered, a bitmap. If approximate answers are fine and memory is critical, a Bloom filter in front of an exact source.

7Conclusion

In this answer, we estimated that HashSet<Long> costs about 60 bytes per element with compressed references, a node, a boxed Long and a share of the table, so 10 million ids take around 600 MB instead of the 80 MB of raw longs. We confirmed the breakdown with a class histogram and compared alternatives: a sorted long[] with binary search, a primitive hash set from fastutil or Eclipse Collections, BitSet or RoaringBitmap for dense or clustered ids, and a Bloom filter when approximate membership is acceptable.

What to say in the interviewAbout 80 seconds aloud

Open with

A HashSet is a HashMap underneath, so each id costs a HashMap node, about 32 bytes with compressed references, a boxed Long, about 24 bytes, and a share of the bucket table, about 7 bytes at 10 million entries.

Then, if they want more

That is around 60 bytes per element, so 10 million ids are roughly 600 megabytes for what is 80 megabytes of raw longs, plus 20 million small objects for the GC to trace. Before changing anything, I would confirm it with jcmd GC.class_histogram, where HashMap$Node and Long would sit at the top, or with JOL in a test.

Then the choice depends on the access pattern. If the set is mostly read, a sorted long array with binary search is 80 megabytes and still sub-microsecond. If it changes often, a primitive set such as fastutil's LongOpenHashSet or Eclipse Collections keeps O(1) operations at about 130 megabytes, at the cost of a dependency and boxing again at Set<Long> boundaries.

If ids are dense, a BitSet is a few megabytes, and RoaringBitmap handles clustered ids well. And if approximate membership is acceptable, for example as a pre-check, a Bloom filter at one percent false positives is about 12 megabytes.

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 keeps a HashSet<Long> of about 10 million user ids in memory and the heap is...": https://scrivio-interview-library.netlify.app/java/sets/68385f732a/