Quick revision
The short answer
I would forbid public library APIs from exposing mutable internal state, including getters that return internal lists, maps or arrays, and forbid java.util.Date and Calendar in new public APIs in favour of java.time. Public value types must be immutable, preferably records whose collection components are copied with List.copyOf or Map.copyOf. Any method that returns a view rather than a copy must say so in its contract. These rules are enforced through API review and static analysis, because an incident costs far more than a copy.
What to remember
In this answer, we saw that the incidents come from shared references to mutable objects, which are hard to trace because the damage happens without any call into the library. The long-term rules are to never expose mutable internal state, to make public value types immutable records with copied collection components, to forbid Date, Calendar, public arrays and mutable static fields in new public APIs, and to document any view as a view. Enforcement through API review, static analysis and contract tests keeps the rules alive, and the cost of a copy is always smaller than the cost of an incident.
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.
I would forbid public library APIs from exposing mutable internal state, including getters that return internal lists, maps or arrays, and forbid java.util.Date and Calendar in new public APIs in favour of java.time. Public value types must be immutable, preferably records whose collection components are copied with List.copyOf or Map.copyOf. Any method that returns a view rather than a copy must say so in its contract. These rules are enforced through API review and static analysis, because an incident costs far more than a copy.
Background to this question
Shared libraries multiply mistakes. A getter that returns its internal list is a one-line bug in one service, but in a library used by forty services it becomes forty places where a caller can corrupt shared state, often in ways that only appear under load. After several incidents, a senior engineer is expected to turn the lessons into durable rules rather than fixing each case. In this answer, we will look at the kinds of incidents involved, the rules I would set and why, the few things I would forbid outright, and how to enforce the rules so they last.
1What the Incidents Have in Common
The incidents in the question all share one pattern: two pieces of code hold a reference to the same mutable object, and one changes it while the other assumes it is stable. A caller passes a list to a library, the library keeps it, and the caller later reuses the list for the next request. Or the library returns its internal map, and a caller removes an entry while filtering. Or a Date passed as a deadline is later moved forward by setTime in unrelated code.
These bugs are hard to diagnose because nothing calls the library when the state changes. The stack trace, if there is one, points to the moment the damage is noticed, not to the moment it was done. That is why prevention through API rules is far cheaper than investigation.
4 messages in order. Play them, or step through them one at a time.
Nothing called the library when the damage was done, which is why these incidents take days to trace.
2Rule: Never Expose Mutable Internal State
The first rule covers both directions across the API. Coming in, a public method or constructor that keeps a collection, array or other mutable argument must copy it. Going out, no public method may return a reference to internal mutable state: not a list, not a map, not an array, and not a mutable object held in a field. Arrays deserve special mention because they can never be made read-only; a public method that returns an internal byte[] or String[] is always a hole.
This rule is what turns the incidents above into impossibilities. If the library copies on the way in, the caller's later changes cannot reach it, and if it never hands out internal objects, callers cannot change it from outside.
3Rule: Public Value Types Are Immutable
Value types are objects that carry data, such as a request, a result, an identifier or a configuration. In public APIs I would require them to be immutable, and the preferred form is a record with a compact constructor that copies collection components. Records make the intent obvious, and the copying line in the constructor is easy to check in review.
The benefit for consumers is that they never have to think about whether they may keep or share a value they received. That makes the library easier to use correctly, which is the point of a shared library.
4What I Would Forbid Outright
Most rules allow judgement, but a few things should simply not appear in new public APIs. java.util.Date and java.util.Calendar are first: both are mutable, both have confusing time zone behaviour, and java.time has replaced them since Java 8. New public methods take and return Instant, LocalDate, ZonedDateTime, Duration and the other java.time types. Code that must talk to legacy APIs converts at the edge with date.toInstant() and Date.from(instant).
Second, public mutable static fields, such as a public static List of defaults, are forbidden, because any code in the JVM can change them. Third, public arrays in fields or return values, as above. Each forbidden item has a clear modern replacement, so the ban costs nothing in expressiveness.
| Item | Rule | Replacement |
|---|---|---|
| Getter returning internal collection | forbidden | store List.copyOf and return it |
| Array in a public return or field | forbidden | List.of or an immutable wrapper |
java.util.Date or Calendar | forbidden in new APIs | Instant, LocalDate, ZonedDateTime |
| Public mutable static field | forbidden | private constant or method |
| Public value type | must be immutable | record with copied components |
| Method returning a view | allowed if documented | say 'live view' in the Javadoc |
5Rule: Document Views Explicitly
Sometimes a library has a good reason to return a view: a live, read-only window onto changing state, such as a registry that grows as plugins load. That is legitimate, but the contract must say so, because a caller who expects a snapshot will be surprised. The Javadoc should state that the returned collection is an unmodifiable view, that it reflects later changes, and whether iterating it is safe while it changes. The default, when nothing is said, is that returned collections are unmodifiable snapshots that will not change.
6Enforcing the Rules
Rules that live only in a wiki fade within a year, so I would enforce them in three layers. API review: every change to a public library API needs approval from a small group of reviewers who check these rules, and a short checklist in the pull request template makes it fast. Static analysis: Error Prone or SpotBugs already flag exposed internal representations (SpotBugs calls these EI_EXPOSE_REP and EI_EXPOSE_REP2), and ArchUnit rules can fail the build when a public API package uses java.util.Date. Tests: a small contract test per value type checks that changing the input after construction does not change the object.
The cost of these rules is a few copies and occasional extra review time. The incidents cost days of investigation each, plus the damage. That comparison is the argument I would give to teams who see the rules as overhead, together with the incident write-ups themselves.
7Follow-up questions
Does copying on every call make the library slow?
Usually not, because the copy happens once at construction and immutable results can be returned without copying. List.copyOf also skips copying inputs that are already immutable. Where a profiler shows a real cost, the fix is usually to restructure, not to remove the protection.
How would you handle existing public APIs that break these rules?
Not by changing them silently, because callers may depend on the current behaviour. I would deprecate the risky method, add a safe replacement, and remove the old one in the next major version, with a migration note. Where a fix does not change the contract, such as copying an input that callers were not supposed to change anyway, it can go into a minor release.
Should the rules apply to internal code too?
As defaults, yes, but enforced strictly only at public library boundaries, where many consumers depend on the code. Inside one service, the team owns all callers and can judge the trade-offs, though the same habits prevent the same bugs.
8Conclusion
In this answer, we saw that the incidents come from shared references to mutable objects, which are hard to trace because the damage happens without any call into the library. The long-term rules are to never expose mutable internal state, to make public value types immutable records with copied collection components, to forbid Date, Calendar, public arrays and mutable static fields in new public APIs, and to document any view as a view. Enforcement through API review, static analysis and contract tests keeps the rules alive, and the cost of a copy is always smaller than the cost of an incident.
Open with
Every incident we had followed the same pattern: two pieces of code shared a reference to a mutable object, one changed it, and the other assumed it was stable, and because nothing called the library at the moment of damage, each one took a long time to trace.
Then, if they want more
So I would set rules at the public API boundary. Nothing public may expose mutable internal state: constructors and methods that keep collections or mutable arguments copy them, and no method returns an internal list, map, array or mutable field.
Public value types must be immutable, ideally records whose compact constructor copies collections with List.copyOf or Set.copyOf, so consumers can keep and share anything they receive. A few things I would forbid outright in new public APIs: java.util.Date and Calendar, replaced by java.time types with conversion at the edges; public arrays; and public mutable static fields.
If a method genuinely needs to return a live view, its Javadoc must say it is a view and that it reflects later changes; otherwise returned collections are unmodifiable snapshots.
Then I would enforce it through API review with a checklist, static analysis such as the SpotBugs exposed-representation checks and ArchUnit rules banning Date in API packages, and small contract tests. A copy costs microseconds; an incident costs days.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- 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
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 "Public library APIs in your company have a history of incidents where callers changed...": https://scrivio-interview-library.netlify.app/java/immutability/3d8eebb9ea/