Video in progress

How do you keep a lookup table with several million entries, used on every request, in memory: a HashMap, a sorted array or off-heap?

The decision depends on the number of entries, how often they change, the latency requirement and the GC budget. For data that doesn't change or rarely updates, primitive arrays plus an atomic swap of an immutable snapshot often give the best balance.

📖 Answer

For example, BIN (card prefix) → bank data, or IP range → country. 5 to 20 million entries, updated once a day, read several times per request.

I compare the options like this:

Option Memory Read GC impact Update
HashMap<Long, Info> the most O(1) millions of objects easy
primitive map (fastutil) 3–4x less O(1) a few big arrays easy
sorted long[] + binary search the least O(log n) almost none full rebuild
off-heap (Chronicle Map, mmap file) outside the heap O(1)/O(log n) none complex

If you have range queries (an IP range), a hash doesn't work at all, and you need a sorted array or a TreeMap.

I often build it like this: the data is fully built as a new snapshot on a background thread, then swapped in instantly through a volatile reference or an AtomicReference. Readers see no lock, and they always see a complete, consistent version.

private volatile BinTable table = BinTable.empty();

void reload() {
    BinTable fresh = BinTable.build(source.fetchAll()); // nobody ever sees a half-built state
    table = fresh;
}

Risks to watch: during the swap, two copies sit in memory temporarily, so plan the heap accordingly. Large arrays become humongous objects in G1, so think about G1HeapRegionSize or splitting the data into chunks.

I go off-heap only when measurements show it is needed: GC pauses are breaking the SLO, or the data doesn't fit in the heap. Otherwise it makes debugging and deploys noticeably more complicated.