In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "the concept of optimistic lock and pessimistic lock in java". In daily operation, I believe that many people have doubts about the concept of optimistic lock and pessimistic lock in java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "optimistic lock and pessimistic lock in java". Next, please follow the editor to study!
What is pessimistic lock and optimistic lock?
Optimism lock corresponds to the fact that optimistic people in life always think about things for the better, while pessimism lock corresponds to life pessimists always think about things for the worse. These two kinds of people have their own advantages and disadvantages, and one kind of person is better than the other according to the scene.
Pessimistic lock
Always assume that in the worst case, every time you go to get the data, you think that someone else will change it, so it will be locked every time you get the data. in this way, others will block until it gets the lock (shared resources are only used by one thread at a time, other threads block, and then transfer resources to other threads after use). Many of these locking mechanisms are used in traditional relational databases, such as row locks, table locks, read locks, write locks and so on. Exclusive locks such as synchronized and ReentrantLock in Java are the realization of pessimistic locking.
Optimistic lock
Always assume that in the best case, every time you go to get the data, you think that others will not change it, so it will not be locked, but when you update it, you will judge whether others have updated the data during this period. You can use the version number mechanism and CAS algorithm to implement it. Optimistic locks are suitable for multi-read applications, which can improve throughput, such as the database provides a mechanism similar to write_condition, which are actually optimistic locks. The atomic variable class under the java.util.concurrent.atomic package in Java is implemented using CAS, an implementation of optimistic locking.
Usage scenarios of two kinds of locks
From the above introduction of the two kinds of locks, we know that each has its own advantages and disadvantages, and one should not be considered better than the other. For example, optimistic locks are suitable for situations where there are few writes (multi-read scenarios), that is, when conflicts really rarely occur, this saves the overhead of locks and increases the overall throughput of the system. However, in the case of overwriting, conflicts often occur, which will cause upper-layer applications to continue to retry, which degrades performance, so it is more appropriate to use pessimistic locks in scenarios with multiple writes.
Two common implementation methods of optimistic lock
Optimistic locks are generally implemented using the version number mechanism or the CAS algorithm.
1. Version number mechanism
Generally, a data version number version field is added to the data table, indicating the number of times the data has been modified. When the data is modified, the version value will be increased by one. When thread A wants to update the data value, it will also read the version value while reading the data. When submitting the update, if the version value just read is equal to the version value in the current database, otherwise, the update operation will be retried until the update is successful.
To take a simple example: suppose there is a version field in the account information table in the database, and the current value is 1, while the current account balance field (balance) is $100.
Operator A reads it out (version=1) at this time and deducts $50 ($100 million 50) from its account balance.
During the operation of operator A, operator B also reads this user information (version=1) and deducts $20 ($100 million) from its account balance.
Operator A completes the modification and adds the data version number by one (version=2), together with the account balance after deduction (balance=$50), and submits it to the database for update. At this time, because the submitted data version is greater than the current version of the database record, the data is updated and the database record version is updated to 2.
Operator B completed the operation and added the version number (version=2) to attempt to submit data (balance=$80) to the database, but when comparing the database record version, it was found that the data version number submitted by operator B was 2, and the current version of the database record was also 2, which did not meet the optimistic lock policy that "the submitted version must be greater than the current version of the record to perform the update". Therefore, the submission of operator B was rejected.
In this way, it is possible for operator B to overwrite the operation result of operator A with the result of old data modification based on version=1.
2. CAS algorithm
Compare and swap (compare and Exchange) is a well-known lock-free algorithm. Lock-free programming, that is, to achieve variable synchronization between multiple threads without using locks, that is, to achieve variable synchronization without thread blocking, so it is also called non-blocking synchronization (Non-blocking Synchronization). The CAS algorithm involves three operands
Memory value V that needs to be read and written
The value A for comparison
New value B to be written
When and only if the value of V is equal to A, CAS updates the value of V with the new value B atomically, otherwise nothing is performed (comparison and substitution is an atomic operation). In general, it is a spin operation, that is, constantly retrying.
The shortcomings of optimistic locks
The ABA problem is a common problem of optimistic locking.
1 ABA problem
If a variable V is read as A value for the first time and checks that it is still A value when preparing for assignment, can we show that its value has not been modified by other threads? Obviously not, because during this time its value may be changed to another value, and then back to A, then the CAS operation will mistakenly assume that it has never been modified. This problem is called the "ABA" problem of CAS operations.
This capability is provided by the AtomicStampedReference class since JDK 1.5, where the compareAndSet method first checks whether the current reference is equal to the expected reference and whether the current flag is equal to the expected flag, and if they are all equal, atomically sets the reference and the value of the flag to the given update value.
(2) long cycle time and high overhead
Spin CAS (that is, if it is not successful, it will loop until it succeeds) if it is not successful for a long time, it will bring a lot of execution overhead to CPU. If JVM can support the pause instructions provided by the processor, then the efficiency will be improved to a certain extent. Pause instructions have two functions. First, it can delay pipelined execution of instructions (de-pipeline), so that CPU will not consume too much execution resources. The delay time depends on the specific version of the implementation. On some processors, the delay time is zero. Second, it can avoid the CPU pipeline being emptied (CPU pipeline flush) caused by memory sequence conflict (memory order violation) when exiting the loop, thus improving the execution efficiency of CPU.
3 can only guarantee the atomic operation of one shared variable
CAS is only valid for a single shared variable, and CAS is invalid when an operation involves spanning multiple shared variables. But since JDK 1.5, AtomicReference classes have been provided to ensure atomicity between reference objects, and you can put multiple variables in a single object for CAS operations. So we can use locks or use the AtomicReference class to merge multiple shared variables into a single shared variable.
Usage scenarios of CAS and synchronized
To put it simply, CAS is suitable for situations with less writes (more reads, fewer conflicts), and synchronized is suitable for situations with more writes (more writes, more conflicts).
In the case of less resource competition (less thread conflict), the use of synchronized synchronous locks for thread blocking and wake-up switching and switching between user-state kernel states is an extra waste of cpu resources, while CAS is based on hardware implementation, does not need to enter the kernel, does not need to switch threads, and has less probability of operation spin, so higher performance can be achieved.
In the case of serious resource competition (serious thread conflict), the probability of CAS spin is higher, which wastes more CPU resources and is less efficient than synchronized.
Add: the synchronized keyword has always been a veteran in the field of Java concurrent programming, and many would have called it a "heavyweight lock" a long time ago. However, after JavaSE 1.6, biased locks and lightweight locks, and various other optimizations that were introduced mainly to reduce the performance consumption of acquiring and releasing locks, became less heavy in some cases. The underlying implementation of synchronized mainly depends on the queue of Lock-Free. The basic idea is to block after spin and continue to compete for locking after competitive switching, which slightly sacrifices fairness, but achieves high throughput. In the case of fewer thread conflicts, the performance is similar to that of CAS; in the case of severe thread conflicts, the performance is much higher than that of CAS.
At this point, the study of "the concept of optimistic lock and pessimistic lock in java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.