Thread Synchronization (2)-pessimistic lock and optimistic lock

Source: Internet
Author: User

The previous blog describes what is thread synchronization, describes the use of synchronized, this blog summarizes pessimistic lock and optimistic lock.

Pessimistic lock, it assumes that as long as there is data access will create a conflict, when a thread reads data must be locked, other users can not operate until the lock is released.

Pessimistic locks are implemented using the data mechanism, where the SQL statement is added "for update" in the query, so that the entire transaction is locked and the next thread operation can be performed only after the end of the transaction execution. This prevents other processes from reading or modifying the data in the table

Select  value from t_table_id where table_name=? for update

Optimistic lock, which assumes that there is no conflict when data is accessed, but checks whether the data integrity is violated when the transaction is committed, and whether the version number is consistent when updating.

For example, the data version in the database is 6, update commits version=6+1, use the version value (=7) compared with the database version+1 (=7), if it is equal, it can be updated, if not unequal it is possible that other programs have updated the record, so an error is returned. Optimistic locking is useful for applications that read from a database.

Optimistic locking is more suitable for less modification of tables, and pessimistic locking is more useful for data modification, which guarantees thread synchronization without generating dirty data.

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.