@synchronized
The essence
@synchronized(obj) { ... } is an Objective-C directive: a critical section that only one thread may enter at a time. Under the hood the runtime keeps a global hash table "object → recursive mutex" and calls objc_sync_enter(obj) / objc_sync_exit(obj) around the block.
Properties:
- Recursive: the same thread may re-enter without deadlock.
- Exception-safe: the lock is released on any exit from the block, including a thrown exception.
- Slow: a global table lookup plus a recursive mutex — noticeably more expensive than
os_unfair_lock. - The key is any object; if the key is
nil, the block runs without a lock (a silent bug). Synchronizing onselfmerges all sections of the class into one lock, and external code can take the same lock and cause a deadlock.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep