Synchronized
JDK 1.5 Implementation with synchronized, wait and notify
synchronized for accessing mutual exclusive resources
A monitor is an additional "superstructure" over a mutex.
Scope of lock
When applied on instance variable or method, lock the object.
When applied on a code block, lock the object.
When applied on static method, lock the entire class.
Internals
Java uses the synchronized keyword to express a monitor.
Downsides
Could only perform operation on a single variable, not multiples
Please see a counter impl based on UNSAFE: https://github.com/DreamOfTheRedChamber/system-design-interviews/blob/master/code/multithreads/Counter.md#unsafe-class-implementation
Could not break deadlock by releasing the lock proactively
For synchronized keyword usage, when the thread could not get all resources, it will enter blocked state and could not do anything else.
Optimization after JDK 1.6
Bias, lightweight and heavyweight lock
Everyone knows that before JDK 1.6, synchronized was a heavyweight lock with low efficiency. So the official started in JDK 1.6, in order to reduce the performance consumption caused by obtaining and releasing locks, we optimized synchronized and introduced the concepts of biased lock and lightweight lock.
These four states will gradually upgrade with competition. But once it is upgraded, it cannot be downgraded. But these conversions are transparent to users who use locks.
Bias lock: only one thread enters the critical section;
Lightweight lock: multiple threads enter the critical section alternately, and the execution ends quickly;
Heavyweight lock: Multiple threads enter the critical section at the same time.
Lock coarsening and elision
Adaptive spinning
Wait and notify methods for coordinating threads
Fundation for asynchronous programming - Future task
Last updated