Synchronized
Last updated
Was this helpful?
Last updated
Was this helpful?
A monitor is an additional "superstructure" over a mutex.
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.
Java uses the synchronized keyword to express a monitor.
For synchronized keyword usage, when the thread could not get all resources, it will enter blocked state and could not do anything else.
References:
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.
Please see a counter impl based on UNSAFE: