Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A market data service keeps 30 million Trade objects in memory. A heap histogram shows that String objects for the exchange code and currency, with only a few hundred distinct values, use several GB. How would you reduce this?

Each of the 30 million trades parsed its exchange code and currency into fresh String objects, so the heap holds tens of millions of copies of a few hundred distinct values. The fix is to canonicalise those values when we parse them: map each value to one shared instance with a private map, or use an enum where the set is fixed, as it is for currencies. String.intern and G1 string deduplication also help but give less control and less saving, and we confirm the result by comparing heap histograms before and after.

Why this question is asked

Memory problems in data-heavy services are rarely about one big object. They are about a small waste repeated tens of millions of times. A market data service is a classic case: every trade carries the same handful of exchange and currency codes, but parsing creates a new String for each field of each trade. Interviewers give this scenario to see whether we can read a heap histogram, do the arithmetic, and choose between the techniques the JVM and our own code offer. In this answer, we will work out where the gigabytes go, apply canonicalisation with a map and with enums, compare it with intern and G1 deduplication, and show how to measure the change.

1Where the Memory Goes

A heap histogram, for example from jcmd <pid> GC.class_histogram, lists each class with its instance count and total bytes. Here it shows around 60 million java.lang.String objects and as many byte arrays, two strings per trade. Yet the data only has a few hundred distinct values: perhaps 40 exchange codes such as XNYS or XLON, and 150 currencies. Almost every one of those strings is a duplicate.

The arithmetic shows why this costs several GB. With compressed object pointers, a String object takes about 24 bytes, and its backing byte array about 16 bytes of header plus the characters, rounded up to 8, so 24 bytes for a three or four letter Latin-1 code thanks to compact strings. That is roughly 48 bytes per string, 96 bytes per trade for the two fields, and 30 million times 96 is about 2.9 GB. If we share one instance per value, each trade holds only two references of 4 bytes each, and the strings themselves take a few kilobytes in total. The exact sizes depend on JVM flags, so we check them against our own histogram.

Shell
$ jcmd 4711 GC.class_histogram | head -5
num #instances #bytes class name
1: 60412233 1449893592 [B // byte arrays behind the strings
2: 60398871 1449572904 java.lang.String
3: 30000000 1200000000 com.acme.md.Trade
Memory for the two code fields of 30 million trades
ApproachPer tradeTotal (approx.)
New String per field (now)2 refs + 2 Strings + 2 arrays, about 104 Babout 3.1 GB
G1 string deduplication2 refs + 2 Strings, arrays shared, about 56 Babout 1.7 GB
Canonical shared Strings2 refs, 8 Babout 240 MB of refs
Enum for currency and exchange2 refs, 8 Babout 240 MB of refs
Sizes assume compressed oops and compact strings; refs are stored in Trade either way.

Notice that the Trade objects themselves are smaller than their strings. That is the signal: the payload we repeat is bigger than the objects that own it.

2Fix 1: Canonicalise While Parsing

Canonicalising means replacing every equal value with one chosen instance, the canonical one. We do it at the single place where strings are created: the parser. A small map from value to instance acts as a flyweight factory.

Java
final class Canonical {
private final ConcurrentHashMap<String, String> pool = new ConcurrentHashMap<>();
private final int limit;
Canonical(int limit) { this.limit = limit; }
String of(String s) {
String existing = pool.putIfAbsent(s, s);
if (existing != null) return existing; // shared instance
if (pool.size() > limit) throw new IllegalStateException("too many distinct values: " + s);
return s;
}
}
Canonical exchanges = new Canonical(1_000);
Trade t1 = parse(line1, exchanges); // exchange "XNYS" stored in the pool
Trade t2 = parse(line2, exchanges);
System.out.println(t1.exchange() == t2.exchange()); // true: one object for both trades

The parse step still allocates a temporary String for each field, but that string dies young in the young generation, which is cheap to collect. Only the canonical one survives into old gen. The limit is a guard: the pool never evicts, so if a bad feed suddenly sends random values, we want a clear error rather than a slow leak. If we can avoid even the temporary allocation, for example by looking up the bytes in a small table before building a String, that is a further gain for very hot paths.

3Fix 2: Use Enums for Fixed Sets

Currencies come from ISO 4217 and exchanges from a known list of market identifier codes, so both are good enum candidates when the service only handles a known set. An enum constant is a flyweight by definition, with exactly one instance, and gives type safety on top: a method that takes a Currency enum cannot be passed an exchange code by mistake.

Java
enum Ccy { USD, EUR, GBP, JPY, CHF /* ... */ }
record Trade(long id, Exchange exchange, Ccy currency, long priceNanos, long qty) {}
Ccy c = Ccy.valueOf(fields[3]); // EUR: the single shared constant
System.out.println(c == Ccy.EUR); // true

But there is a catch: a new currency or venue from the feed now needs a code change and a release, and Enum.valueOf throws IllegalArgumentException on an unknown value. For values that change often, the map approach is the better fit, or the JDK's own java.util.Currency, which already returns one shared instance per code.

4What String.intern and G1 Deduplication Give

String.intern() also returns a canonical instance, using the JVM's string table. It works, and the table is reclaimed by GC in modern JVMs, but it is shared by the whole JVM, its size is set with a JVM flag, and we cannot put a limit or a metric on our own usage. A private map gives us that control and keeps different data sets apart.

G1 string deduplication, enabled with -XX:+UseStringDeduplication (supported by other collectors too in recent JDKs, so check your version), works differently. During GC it finds String objects with equal contents and makes them share one backing byte array. That saves the arrays, roughly half of our waste, with no code change. But the 60 million String objects remain, so it cannot match canonicalisation. It also costs some background GC work, and it only processes strings that have survived a few collections.

Step throughChoosing a technique for duplicated values
  1. Is the set of values fixed and small?Currencies, venues, statuses
    YesUse an enumNoNext question
  2. Can we change the parsing code?One place creates the strings
    YesCanonicalise with a bounded mapNoNext question
  3. Is a JVM-wide table acceptable?No limits or metrics of our own
    YesString.internNoTurn on string deduplication
  4. Measure with a heap histogramCompare counts and bytes before and after

4 steps in order. Play them, or step through them one at a time.

5Measuring Before and After

We take a histogram under realistic load before the change, deploy the canonicalised parser to one instance, and take another after a full GC so the young temporary strings are gone. We expect the String count to fall from about 60 million to a few hundred plus whatever else the service uses, and old-generation occupancy to fall by roughly the 2.9 GB we estimated. We also watch allocation rate and GC pause times, because the temporary strings from parsing are still allocated. Keeping the histogram commands in the runbook means the next regression is found the same way.

6Follow-up questions

Why not make the Trade fields char arrays or ints?

Encoding the code as an int or short id is the most compact option and can make sense in very large in-memory stores, but it pushes decoding into every reader and loses readability. A shared reference already costs only 4 bytes with compressed oops, so canonical Strings or enums capture almost all of the saving with ordinary code.

Is the canonical map thread-safe?

Using ConcurrentHashMap.putIfAbsent makes it safe: if two threads parse XNYS at once, one wins, and both get back the same instance afterwards. Strings are immutable, so sharing them across threads needs no further locking.

Could compact strings alone have solved this?

Compact strings, on by default since Java 9, already store Latin-1 text with one byte per character instead of two, and the numbers above assume them. They shrink each copy but do not remove copies, so with 60 million duplicates the waste stays in the gigabytes.

7Conclusion

In this answer, we saw that the gigabytes came from tens of millions of duplicate String objects, two per trade, for a few hundred distinct values. Canonicalising at parse time with a bounded map, or using enums for fixed sets like currencies, cuts that to a reference per field. String.intern works but uses a JVM-wide table we cannot control, and G1 string deduplication shares only the byte arrays while the String objects stay. Heap histograms before and after the change prove the saving.

What to say in the interviewAbout 100 seconds aloud

Open with

The histogram tells me that each trade has its own String objects for exchange and currency, even though there are only a few hundred distinct values. So nearly all of those 60 million strings are duplicates.

Then, if they want more

With compressed oops, each short string costs about 48 bytes including its byte array, so two per trade times 30 million is roughly 3 GB. My fix is to canonicalise at parse time.

The parser passes each value through a small ConcurrentHashMap that returns the first instance it saw for that value, so every trade ends up holding a reference to one shared String. I would put a limit on that map so a bad feed with random values fails loudly instead of leaking.

For currency, and probably exchange, the set is fixed, so an enum is even better, because each constant is a single instance and we get type safety, but then new values need a release. String.intern would also deduplicate, but it uses the JVM-wide string table, so I get less control and no metrics of my own.

G1 string deduplication is a zero-code option, but it only shares the backing byte arrays; the String objects themselves remain, so it saves maybe half.

To prove the change works, I would take a class histogram before, deploy to one instance, and take another after a full GC, expecting the String count to drop from tens of millions to a few hundred and old gen to shrink by about the amount I estimated.

About this answer

Last updated
12 November 2026
Versions it names
Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. 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 market data service keeps 30 million Trade objects in memory. A heap histogram shows...": https://scrivio-interview-library.netlify.app/java/structural-patterns/ce3a6021aa/