Scrivio Interview library
LeadershipPrincipal7 min read · updated 12 November 2026

Memory-saving techniques such as flyweights and interning matter at scale. Over years, how do you decide whether to remove duplication in application code or rely on runtime features such as compact strings, string deduplication and possible future value classes?

Runtime features such as compact strings and string deduplication should be the default, because they apply to the whole fleet with no code change and get better with every JDK upgrade. Application-level flyweights and canonicalisation can save far more, but only in specific hot spots, and they bring immutability rules and extra code to maintain. So we let production heap histograms tell us where the largest duplicated data is, use runtime options first, write our own sharing only for proven hot spots, and revisit those choices as the JDK evolves, since features such as value classes may make some manual tricks unnecessary.

Why this question is asked

At small scale, memory tuning is a one-off task for one service. At the scale of hundreds of services and thousands of JVMs, it becomes a standing decision with real money attached: heap size drives instance size, and instance size drives the cloud bill. The difficult part is not knowing the techniques but deciding who applies which one, and when the answer should change. Interviewers ask this of senior engineers to hear how they weigh broad, cheap, automatic gains against narrow, expensive, manual ones over years. In this answer, we will compare what the runtime gives us with what application code can do, describe how evidence from production should drive the choice, set a default policy, and plan how to revisit it as the JDK changes.

1What the Runtime Already Does for Us

Several JVM features remove duplication without us writing any code. Compact strings, on by default since Java 9, store Latin-1 text in one byte per character instead of two, which roughly halves the size of most strings in business applications. String deduplication, originally for G1 and now available with other collectors in recent JDKs (check your version), lets the garbage collector find strings with equal contents and make them share one backing array. Compressed object pointers keep references at 4 bytes on heaps under about 32 GB. And newer JDKs keep adding ideas, such as compact object headers, which shrink every object header, introduced as experimental in JDK 24 and made a product feature in JDK 25.

The strength of these features is reach. One JVM flag, or one JDK upgrade, applies to every service in the fleet, including libraries we do not own. They also improve without our effort: each JDK release tends to make them faster or broader. Their weakness is that they are generic. Deduplication shares only the byte arrays, not the String objects themselves, and it costs background GC work.

2What Application Code Can Do That the Runtime Cannot

Inside our own code we know things the JVM does not. We know that a field can only hold one of 150 currency codes, or that an order status is one of six values. With that knowledge we can use enums, canonicalise values with a private map when parsing, or replace a repeated object graph with a shared immutable one. In a hot spot, such as a cache of 30 million trades, this can save several GB in one service, far more than deduplication, because it removes whole objects, not just their arrays.

But every manual flyweight has costs that last for years. The shared objects must be immutable, and a future developer who adds a setter breaks every user at once. Canonical maps that never evict can leak memory when the input is not as bounded as we thought. Identity comparisons sneak in, because == happens to work on shared instances. And the code is harder to read for people who do not know why it is there. So the saving must be large enough to pay for that, and only measurement can tell us.

Runtime features versus application-level sharing
AspectRuntime featuresApplication flyweights
ReachEvery service, every libraryOne code path at a time
Code changeNone, a flag or an upgradeParser, model and tests change
Size of savingModerate, spread everywhereLarge, in one hot spot
Ongoing costSome GC workImmutability rules, review, leaks to guard
Improves over timeYes, with each JDKOnly when we change it

3Letting Production Evidence Decide

The decision starts with data from production, not from a code review. We collect class histograms (jcmd GC.class_histogram) and, for deeper analysis, heap dumps from representative instances under real load, and we look at which classes dominate the old generation and how many duplicates they contain. Heap analysis tools can report duplicate strings directly. A fleet-wide view helps: if 80 percent of services spend 20 percent of their heap on duplicate strings scattered everywhere, that argues for a runtime flag. If one service spends 40 percent of a 64 GB heap on one field of one class, that argues for code.

We also translate memory into money and risk before acting. Saving 3 GB on a service that runs 40 instances may let us drop an instance size and pay for the work in months. Saving 200 MB on a service with two instances rarely justifies a custom flyweight.

Step throughDeciding how to remove duplication
  1. Collect histograms from productionRepresentative load, after full GC
  2. Is duplication spread across many services?Strings everywhere, no single owner
    YesEnable or tune a runtime featureNoLook for a hot spot
  3. Does one structure dominate one service?For example 30M objects with repeated fields
    YesConsider application-level sharingNoLeave it; revisit next review
  4. Is the saving worth the lasting cost?Instance size, GC, money
    YesBuild it with tests and a limitNoPrefer the runtime option
  5. Measure again after the changeRecord the result in the guide

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

4A Default Policy for the Organisation

The guidance we would publish is simple. First, keep services on a current LTS JDK, because that is the cheapest memory work there is. Second, use runtime options such as string deduplication where histograms show widespread duplicate strings, and enable them in the shared base image or service template so teams get them without effort. Third, write application-level sharing only for a proven hot spot, with the histogram attached to the design review, a bounded cache, immutable shared types and a test that fails if someone compares by identity.

The reason for this order is that runtime features compound across the fleet and cost almost nothing to maintain, while manual sharing is a local optimisation that every future maintainer must understand. Starting with the broad, cheap option and reserving the narrow, expensive one for clear wins keeps the total cost of the codebase low.

5Revisiting the Choice as the JDK Changes

Manual techniques are not forever. Project Valhalla is working on value classes, objects without identity that the JVM may store flat inside arrays and other objects. If and when they land in a JDK we use, a record of a few fields might take far less memory with no flyweight at all, and some of our canonical maps could become unnecessary. Since the final shape and release are not settled, we should not design around them today, but we should keep our hot-spot code isolated behind small types so it is easy to change later.

So once or twice a year, typically when a new LTS arrives, we rerun the histograms on the hot spots, test whether the manual sharing still earns its keep under the new JDK, and delete code that no longer pays. Recording every manual flyweight in one place, with its measured saving, makes that review quick.

6Follow-up questions

Would you ever turn string deduplication on for all services?

Only after checking that it helps. It costs some CPU in the collector and only works on strings that survive long enough, so services with mostly short-lived strings gain little. Turning it on in the base image for long-lived, string-heavy services, with a way for teams to opt out after measuring, is a reasonable default.

How do you stop manual flyweights from becoming a hidden bug source?

We make the shared types immutable records, keep the factory in one class with a bounded size and a metric, and add tests or static analysis rules that reject == comparisons on those types. The design note with the original histogram explains why the code exists, so nobody removes it or copies it without reason.

Is it worth upgrading the JDK just for memory?

Often yes, at fleet scale. Features like compact object headers in JDK 25, once enabled, shrink every object, and better collectors reduce the heap headroom we need. One upgrade across hundreds of services can save more than many local optimisations, and it brings security and performance fixes too.

7Conclusion

In this answer, we saw that runtime features like compact strings, string deduplication and newer header and value-class work reach the whole fleet without code and improve with each JDK, while application-level flyweights save much more in a single hot spot but bring lasting complexity and immutability rules. Production heap histograms decide where the large duplicates are. The policy is runtime options first, manual sharing only for proven hot spots, and a regular review as the JDK changes.

What to say in the interviewAbout 90 seconds aloud

Open with

I treat this as a portfolio decision rather than a coding question. Runtime features like compact strings, string deduplication and compact object headers apply to every service, including libraries we do not own, with no code change, and they get better with each JDK.

Then, if they want more

Application-level techniques, like enums or a canonicalising map in a parser, can save far more in one hot spot, sometimes gigabytes in a single service, but they need immutable shared types, bounded caches and people who remember why the code exists. So I start from evidence.

We take class histograms and occasional heap dumps from production and see where duplicates really are. If duplicate strings are spread thinly across many services, that is a job for a runtime option in the base image.

If one structure dominates one service's heap, I consider application-level sharing, but only after translating the saving into instance sizes or money and comparing that with the maintenance cost.

My default policy would be: stay on a current LTS, turn on runtime options where measurements show they help, and allow manual flyweights only for proven hot spots, with the histogram in the design review and tests guarding identity comparisons. Then I revisit at each LTS upgrade, because the JDK keeps moving.

Value classes from Valhalla may eventually make some of these tricks unnecessary, so I keep that code isolated and delete it when it no longer pays.

About this answer

Last updated
12 November 2026
Versions it names
Java 25, Java 24, 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 "Memory-saving techniques such as flyweights and interning matter at scale. Over years...": https://scrivio-interview-library.netlify.app/java/structural-patterns/c4a7d1f76a/