Java programming: The difference between pessimistic lock and optimistic lock and the usage scene

Source: Internet
Author: User
Defined:

Pessimistic lock (Pessimistic lock):
Every time you get the data, you worry about the data being modified, so lock it every time you get the data, make sure the data will not be changed by others when you use it, and unlock the data when you're done. Because the data is locked, other threads that read and write to that data during the period will wait.

Optimistic lock (Optimistic lock):
Every time you get data, you don't worry about the data being modified, so you don't lock it up every time you get the data, but when you update the data, you need to know if the data has been modified by someone else. If the data is modified by another thread, the data is not updated and the data is updated if the data is not modified by another thread. Because the data is not locked, the data can be read and written by other threads.

Applicable scenarios:

Pessimistic lock: more suitable for writing more frequent scenes, if there is a large number of read operations, each time the reading will be locked, which will increase the cost of a large number of locks, reducing the system's throughput.

Optimistic lock: More suitable for reading more frequent scenes, if there is a large number of write operations, the likelihood of data conflicts will increase, in order to ensure the consistency of data, the application layer needs to constantly regain data, which will increase the number of query operations, reducing the system's throughput.

Summary: Both have advantages and disadvantages, read frequently use optimistic lock, write frequent use pessimistic lock.

Java programming: The difference between pessimistic lock and optimistic lock and the usage scene

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.