"Java multithreading" pessimistic lock and optimistic lock

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.