What advantages do immutable objects provide?
Immutable objects are objects that cannot be changed after creation. Instead of modifying them, a new object with new data is created.
Basic Level
Immutable objects are objects that cannot be changed after creation. Instead of modifying them, a new object with new data is created.
Main advantages
- Easy to understand — an object is always in one state, no need to track modification history
- Safety — no one can accidentally change the object’s data
- Easier to test — the object always behaves the same way
Simple example
String s1 = "Hello";
String s2 = s1.concat(" World"); // s1 is unchanged, s2 is a new string
// s1 is still "Hello"
Cost of immutability
- Excessive GC pressure with mass object creation (1000 concatenations = 1000 objects)
- Copying overhead for large structures (deep copy O(n))
- Inconvenient API — every change = creating a new object
Intermediate Level
Thread-safety without locks
Immutable objects are thread-safe by default:
- Multiple threads can simultaneously read an object without risk of Race Condition
- No need for
synchronized,ReentrantLock— no locks, no Deadlocks
Ideal keys for HashMap
The object’s hashCode() will never change — the object won’t get “lost” in the hash table bucket.
No side effects
Methods return new objects instead of modifying existing ones. You can pass an object to any method and be confident that its contents won’t change.
Reuse (Flyweight pattern)
- String Pool — identical strings share one object
- Integer Cache — numbers from -128 to 127 are reused
Boolean.TRUE/Boolean.FALSE— the only instances
Example: safe return from getter
public final class Config {
private final Map<String, String> properties;
public Config(Map<String, String> properties) {
this.properties = Map.copyOf(properties);
}
public Map<String, String> getProperties() {
return properties; // safe — Map.copyOf returned an immutable map
}
}
Advanced Level
Java Memory Model Guarantees
Fields marked as final receive special visibility guarantees. After the constructor completes, the reference to the object is considered safely published — any thread will see the correct values without additional memory barriers.
Impact on Garbage Collection
- Immutable objects are created in Young Generation and die there
- Modifying an old object in Old Generation requires a Write Barrier — immutable objects eliminate such overhead
- References are set once at creation — GC doesn’t need to track inter-generational changes
Scalability in distributed systems
- Lock-free access — reading without locks eliminates contention between threads, which under high contention can reduce throughput by 50-90%.
- Side-effect free — aligns with functional programming principles
- Cache Friendly — safe caching without risk of data “poisoning”
Summary for Advanced
- Main advantage: reduced cognitive load in a multi-threaded environment. No need to think: “Who else might change this object?”. You read an object — and are confident it won’t change under you.
- The win from eliminating locks outweighs allocation costs under read-heavy workloads. Instead of
synchronizedon every read — just read without locks. Under write-heavy workloads, allocating new objects can become a bottleneck. - Immutability is the foundation for reliable Domain Models
- In high-load systems, immutability wins due to scalability
Interview Cheat Sheet
Must know:
- Thread-safety without locks — no race conditions, no Deadlocks
- Ideal keys for HashMap —
hashCode()never changes - Flyweight pattern — String Pool, Integer Cache, object reuse
- Side-effect free methods — align with functional programming principles
- Safe publication through
finalfields — JMM visibility guarantees - Lock-free reading eliminates contention (50-90% throughput under high contention)
- GC benefits: no Write Barriers, Young Generation objects cleaned up for free
- Cache Friendly — safe caching without risk of data “poisoning”
Frequent follow-up questions:
- Why are immutable objects thread-safe? — No writes after creation = race condition impossible
- How does immutability affect GC? — Short-lived objects are cleaned up in Minor GC, no cross-generation references
- What is Flyweight? — Pattern for reusing identical objects (String Pool, Integer Cache)
- Is there a cost to immutability? — Excessive GC pressure with mass creation, copying overhead
Red flags (DO NOT say):
- “Immutability always slows things down” — on read-heavy workloads without locks it’s faster
- “synchronized is needed for immutable objects” — they are thread-safe by default
- “Immutable objects can’t be cached” — they are IDEAL for caching
- “Flyweight is only for strings” — Integer, Boolean also use this pattern
Related topics:
- [[1. What is an immutable object]]
- [[6. Why are immutable objects thread-safe]]
- [[22. What advantages do immutable objects have for caching]]
- [[23. How does immutability affect performance]]