synchronized and monitors
synchronized in Java locks a monitor (object). Only one thread holds the lock. Visibility and atomic sections are thus ensured (happens-before).
Coarse locks can slow down performance; fine locks are prone to errors.
Where used
Classic JVM mutual exclusion. This is foundational before moving on to java.util.concurrent, locks, and lock-free structures.
Depth
Any Java object can serve as a monitor. A synchronized block acquires its intrinsic lock, executes the protected section, and releases the lock upon exit, even in the case of exceptions. Only code that uses the same monitor collectively protects the same invariant.
Exiting a monitor publishes previous changes; later acquiring the same monitor makes them visible. Synchronized thus regulates both mutual exclusion and memory order. Choosing a private, stable lock object prevents unintended external lock coupling.
Difficulty levels
- Determine the monitor of an instance method and a static method.
- Protect all accesses to an invariant with the same lock.
- Balance the scope of locking between safety and parallelism.
Pitfalls
Two different lock objects do not protect against each other. Publicly accessible or changing lock objects are also risky. Multiple locks in inconsistent order can lead to a deadlock.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Intermediate
- Completed: 0 users