How do you design a correct immutable class for a multi-threaded service?
Reviewed by Gurusankar M.
β‘ Short Answer
Make the class final, all fields private final, no setters, initialize in the constructor, and defensively copy any mutable inputs/outputs (collections, dates). Java records do most of this β but you must still deep-copy mutable members.
βCoffee Chat Question
Concept Made Simple
βHow do you design a correct immutable class for a multi-threaded service?β
π§ Mind Map Answer
Remember It Faster
β¨οΈHands-on Keyboard
Learn by Doing
public final class Money {
private final long cents;
private final List<String> tags;
public Money(long cents, List<String> tags) {
this.cents = cents;
this.tags = List.copyOf(tags); // defensive copy in
}
public List<String> tags() { return tags; } // already unmodifiable
}π₯What If?
Think Beyond the Expected
A record holds a List field β is it truly immutable?
No. The record reference is final, but the List itself is still mutable, so callers can change its contents. You must copy it in the compact constructor (List.copyOf) and expose an unmodifiable view.
πReal World
Immutable value objects (Money, DateRange, Coordinates) are shared freely across threads with zero synchronization β the backbone of thread-safe domain models and functional-style services.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βStoring a mutable collection/date without copying
- βReturning the internal mutable reference from a getter
- βForgetting final on the class, allowing a mutable subclass
β Best Practices
- βDefensive-copy mutable inputs and outputs
- βPrefer records + List.copyOf for value objects
- βProvide with-style copy methods for 'changes'
πFollow-up Questions
- 1How do records help, and where do they fall short?
- 2How do you 'modify' an immutable object (with-er / copy)?
- 3Why are immutable objects inherently thread-safe?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: OOP (Core Java) Interview question: "How do you design a correct immutable class for a multi-threaded service?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.