Java Developer interview question
How do you make Java code thread-safe?
Thread safety requires protecting shared invariants through immutability, confinement, atomic classes, locks, or concurrent collections; visibility and compound operations matter, not only individual reads and writes.
Direct answer
What a strong answer covers
How it works
Thread safety is about invariants, not individual statements. The Java memory model only guarantees that one thread sees another’s writes through synchronisation, volatile, or the happens-before edges that java.util.concurrent establishes. The cheapest safe designs avoid sharing: immutable objects, thread confinement, and message passing. Where state must be shared, atomic classes handle single variables, concurrent collections handle maps and queues, and explicit locks guard compound operations such as check-then-act.
Example
A counter incremented with count++ from many threads loses updates because the increment is three operations; replacing it with AtomicLong or a LongAdder fixes it without a lock. A cache implemented as HashMap with synchronized get and put is still wrong for putIfAbsent semantics, whereas ConcurrentHashMap.computeIfAbsent performs the check and insert atomically.
Common mistakes
- Marking a field volatile and assuming compound updates on it are atomic.
- Synchronising every method and creating a bottleneck instead of protecting the specific invariant.
- Publishing a partially constructed object to another thread by leaking this from the constructor.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.