Immutability and defensive copying
16 questions in 5 subtopics.
Designing immutable classes
List the rules for writing an immutable class in Java, and explain why each rule matters.This record is meant to be immutable:record Team(String name, List<String> members) {}. A caller does team.members().add("x") and another thread sees the change. Why, and how do you fix it?You are designing a Money value type used across billing services. What decisions do you make about immutability, equality, scale and arithmetic?Your organisation has a mix of mutable JavaBeans with setters and newer immutable records across domain models. What standard would you set for new code and how would you handle existing code and frameworks that expect setters?Defensive copies
Find the bug and fix it:final class Period {
private final Date start, end;
Period(Date s, Date e) {
if (s.after(e)) throw new IllegalArgumentException();
start = s;
end = e;
}
Date start() {
return start;
}
}
Unmodifiable vs immutable collections
What is the difference betweenCollections.unmodifiableList(list), List.copyOf(list) and List.of(...)? Show a case where an unmodifiable list still changes.An unmodifiable list of mutable objects such as List<StringBuilder> is still not immutable. Explain shallow versus deep immutability, and how you would make a deep immutable structure.Java chose to express unmodifiable collections as run-time behaviour of the same List and Map interfaces rather than as separate immutable types, unlike Guava's ImmutableList or Kotlin's read-only interfaces. How should that choice shape your organisation's conventions?Immutability and thread safety
Why are immutable objects thread-safe, and what does the Java Memory Model guarantee about final fields? When can an object with final fields still be seen in an inconsistent state?Several services share a mutable in-memory product catalogue that background threads refresh, and you have seen torn reads andConcurrentModificationException in production. Across the teams that own these services, how would you redesign catalogue handling?You are designing a configuration system that many request threads read while an admin endpoint occasionally updates it. Compare a mutable config object with locks against an immutable snapshot swapped through an AtomicReference.Builders for immutable objects
Write a builder for an immutableHttpRequestSpec with a required url and optional timeout and headers. Where should validation happen?Records have no built-in builder. For a record with eight components, compare a hand-written builder, Lombok @Builder, a generated builder and wither methods. Which would you choose for a shared API?Java has been moving toward immutable data with records, List.of, and value classes being explored in Project Valhalla. How do you guide a large codebase so today's design choices age well?No question matches these choices.