Java programming: Pessimistic lock, optimistic lock difference and the use of the scene __ algorithm

Source: Internet
Author: User
Defined:

Pessimistic lock (Pessimistic lock):
Every time you get the data, you will worry about the data is modified, so every time you get the data will be locked, to ensure that in their own use of the data will not be modified by others, using the completion of the data unlock. Because the data is locked, other threads that read and write to the data are waiting.

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

Pessimistic lock: more suitable for write operations more frequent scenes, if a large number of read operations, each read will be added lock, which will increase the cost of a large number of locks, reducing the system throughput.

Optimistic lock: More suitable for reading operations more frequent scenes, if a large number of write operations, the likelihood of data conflict 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 throughput.

Summary: Both have advantages and disadvantages, read frequently use optimistic lock, write frequently use pessimistic 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.