In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the meaning of pessimistic lock and optimistic lock in java concurrent programming. It is very detailed and has a certain reference value. Interested friends must read it!
Pessimistic lock
Pessimistic lock is a kind of lock that is often used in development, such as ReentrantLock and synchronized. It always assumes that other threads will modify the data when they take the thread, so they will lock it every time they get the data, so that other threads will block if they want to get the data. As shown in the figure:
Synchronized is an implementation of pessimistic locks, which we usually use like this:
Private static Object monitor = new Object ()
Public static void main (String [] args) throws Exception {
/ / Lock a block of code
Synchronized (monitor) {
}
}
/ / Lock instance method. The lock object is this, that is, the instance itself.
Public synchronized void doSome () {
}
/ / Lock static method. The lock object is this class, namely XXX.class.
Public synchronized static void add () {
}
When we analyze it in terms of the simplest synchronous code block, we actually apply synchronized to a given instance object monitor, that is, the current instance object is the lock object. Every time a thread enters the code block wrapped by synchronized, it will require the current thread to hold the monitor instance object lock. If another thread is currently holding the object lock, the new thread must wait. This ensures that only one thread executes the code block wrapped in the synchronized at a time.
As can be seen from the above analysis, pessimistic locks are exclusive and exclusive, and resources will be locked as long as they are manipulated. Assuming that you read more and write less, the effect of using pessimistic locks is not very good. This leads to the optimistic lock that we will talk about next.
Optimistic lock
Optimistic lock, as its name implies, always assumes the best-case scenario. Every time the thread goes to get the data, it thinks that others will not modify it, so it will not lock it. But when updating, it will judge whether others have updated the data during this period. If the data has not been updated, the current thread will successfully write the modified data. If the data has been updated by other threads, different operations (such as error reporting or automatic retry) are performed depending on the implementation. As shown in the figure:
Generally, optimistic locking is realized through lock-free programming in java, and the most common is the CAS algorithm. For example, the increment operation of atomic classes in Java concurrent package is realized through CAS algorithm.
CAS algorithm actually means Compare And Swap (compare and exchange). The goal is to update the memory value to the desired value, but there is a condition that the memory value must be the same as the expected original memory value. In terms of expansion, we have three variables, the memory value M, the expected memory value E, and the update value U, and M is updated to U only when the memory value E is updated.
The optimistic locking implemented by the CAS algorithm is used in many places, such as the atomic class AtomicInteger class of concurrent packages. The CAS algorithm is used when it is self-increasing.
Public final int getAndIncrement () {
Return unsafe.getAndAddInt (this, valueOffset, 1)
}
/ / var1 is the this pointer
/ / var2 is offset
/ / var4 is self-incremental
Public final int getAndAddInt (Object var1, long var2, int var4) {
Int var5
Do {
/ / get memory, which is called the expected memory value E
Var5 = this.getIntVolatile (var1, var2)
/ / the result of var5 + var4 is the update value U
/ / the JNI method is used here, and each thread compares its own memory value M with the expected value of var5.
/ / if the same, update to var5 + var4 and return true to jump out of the loop.
/ / if different, update the memory value M to the latest memory value, and then spin until the update is successful
} while (! this.compareAndSwapInt (var1, var2, var5, var5 + var4))
/ / return the updated value
Return var5
}
Public final native boolean compareAndSwapInt (Object var1, long var2, int var4, int var5)
So you can see that the CAS algorithm is actually unlocked. The advantage is that in the case of more reading and less writing, the performance is better. Then the disadvantage of CAS algorithm is also obvious.
The problem follows the ABA. Thread C changes the memory value A to B and then changes it to A, while thread D thinks that the memory value A has not changed. This problem is called the ABA problem. The solution is simple: add the version number before the variable, and the version number of the variable is + 1 each time the variable is updated, that is, A-> B-> A becomes 1A-> 2B-> 3A. In the case of writing more and reading less, that is, updating the data frequently, it will cause other threads to fail frequently, and it will enter spin, which will take up CPU resources. If the competition for resources is fierce, multithreading spins for a long time, resulting in the consumption of resources. Working with scen
In the scenario of more reading and less writing, there are few conflicts during updates, and optimistic locks are used to reduce the overhead of locking and releasing locks, which can effectively improve the performance of the system.
In contrast, in a scenario with more writes and less reads, the use of optimistic locks will often cause conflicts during updates, and then the thread will loop and retry, which will increase the CPU consumption. In this case, it is recommended to use pessimistic locks.
That's all of the article "what are pessimistic locks and optimistic locks in java concurrent programming?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.