About
Synchronization insures thread safety by preventing the same code being run by two different threads at the same time.
When a code (object, method) has a synchronized property, if a thread enter a synchronized method, it will get a lock on it.
It's a lock mechanism but at the code level (not at the state/value leve, see Data Concurrency - Atomic Variable Access)
If an object is visible to more than one thread, all reads or writes to that object's variables must be done through synchronized code.
Synchronization can introduce thread contention, which occurs when two or more threads try to access the same resource simultaneously.
Synchronization has two aspects:
- enforcing exclusive access to an object's state
- and establishing happens-before relationships that are essential to visibility.
This strategy is effective, but can present problems with liveness.
Articles Related
Synchronize the activities of threads
Warying ways to synchronize the activities of threads.
- delayed tasks,
- barriers,
- …