One: Pessimistic lock
Pessimistic lock, that is, regardless of whether there is a multi-threaded conflict, as long as there is such a possibility, on each access is locked, locking will lead to the contention between the lock, there will be a fight to win or lose, the loser waits.
Syncrhoized is an exclusive lock, that is, the thread that occupies the lock can execute, and the thread that requests the lock will only suspend waiting until the thread that occupies the lock releases the lock before it wakes up, gets the lock, and executes it. Because there is a lot of overhead in the process of suspending and resuming execution, and when a thread is waiting for a lock, it cannot do anything. So syncrhoized is a pessimistic lock, all the multi-threaded with syncrhoized lock will be caused by the result of the lock to suspend, wake up and other costs.
Two: Optimistic lock
Hold the lock after the lock is held in case the thread again requests that the lock cause unnecessary unlocking and locking overhead, or assume that there is no conflict to complete the synchronization code block if the conflict is recycled retry, or take the request lock failed to suspend immediately but slightly wait to try to get the wait policy again, to reduce the thread because of hang, block, The overhead of waking (a scheduled switchover of the CPU).
Bias Lock, lightweight lock (CAS polling), spin lock is an optimistic lock based on the above ideas.
In a multi-threaded locking mechanism, the JVM will first attempt an optimistic lock, and the pessimistic lock is not invoked until it fails.
"Java multithreading" pessimistic lock and optimistic lock