Make code thread safe
Filed under Amazon
Free read 1 of 3Identify critical sections where shared mutable state is accessed or modified.
The question
Take a provided non-thread-safe piece of code and refactor it to implement proper thread safety using synchronization primitives.
Constraints
- Solution must avoid deadlocks and minimize lock contention.
- Must use standard synchronization mechanisms available in the language.
Approach
Identify critical sections where shared mutable state is accessed or modified.
Apply a single global lock or monitor across all methods, which serializes access and hurts concurrency.
Use specialized concurrent data structures, read-write locks, or atomic variables to allow safe concurrent execution.
Nested locks leading to potential deadlocks, or race conditions during initialization.
Tips
- What they are testing: Test with multiple concurrent worker threads performing read and write operations simultaneously.
- Common mistake: Over-locking entire methods when finer-grained locking or thread-safe collections would suffice.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.