Interview conceptCoding & Algorithms

Concurrency And Thread Safety

Asked of: Software Engineer

Last updated

What's being tested

Interviewers assess your ability to reason about race conditions, choose correct synchronization primitives, and implement thread-safe algorithms without sacrificing performance. Expect to justify tradeoffs between coarse-grained locks, lock-free approaches, and use of concurrent collections while avoiding deadlocks and livelock.

Patterns & templates

  • Guarded by lock — wrap shared-state access with `synchronized`/`ReentrantLock`; simple, correct, but may reduce concurrency.

  • Fine-grained locking / lock striping — partition state to reduce contention; watch increased complexity and ordering rules.

  • Lock-free CAS loops — use `AtomicInteger`/`AtomicReference` with compare-and-set for O(1) updates; retry-loop liveness cost must be considered.

  • Double-checked locking — use `volatile` plus check-lock-check idiom for lazy init; correct in Java 5+ with `volatile`.

  • Producer-consumer — use `BlockingQueue`/`Semaphore`/`Condition` to coordinate handoff without busy-waiting; avoids manual wait/notify pitfalls.

  • Reader–writer optimization`ReadWriteLock` for many-read/few-write patterns; writers starve readers or vice versa if misconfigured.

  • Thread pools — prefer `ExecutorService` (`ThreadPoolExecutor`) over raw `Thread` for resource control, backpressure, and lifecycle management.

Common pitfalls

Pitfall: Assuming `++` on a shared integer is atomic; it's read-modify-write and causes lost updates without synchronization.

Pitfall: Holding multiple locks without a consistent global order, which easily produces deadlock under concurrency.

Pitfall: Over-synchronizing for correctness but causing severe throughput degradation; measure contention with profiler or metrics.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Related concepts