In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains the "detailed introduction of all kinds of locks in Java". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "detailed introduction of various locks in Java".
What is the use of the lock?
Having said so much, it is still not clear what the use of locks is. At this point, we have to think deeply about why we use locks, we use cell phone locks to protect our privacy, door locks are used to ensure the security of our property, and exactly we use locks for security.
So in life, we can add locks to protect our privacy and property security, so what is the use of locks in Java?
Locks in Java
Locks in Java are precisely for security, but the difference is that locks in Java are needed to ensure concurrency. So locking in Java is not only to ensure concurrency security, but also to solve the three problems of consistency, atomicity and order in memory. A variety of locks are provided in Java, and each lock has its own characteristics and scope of application. So we all need to be familiar with the difference and principle of locks in order to use them correctly.
Optimistic lock and pessimistic lock
Pessimistic lock
Optimistic lock and pessimistic lock I wrote related articles when I just started to write, so let's reintroduce them here.
Pessimistic lock, as its name is, is pessimistic, it feels that every time data is accessed, it may be modified by other people (threads), so resources are locked when they are accessed, in this way to ensure that resources will not be modified by other threads when they are accessed. In this way, other threads will have to block if they want to get the resource until the current thread releases the lock. The implementation of pessimistic lock in Java includes the synchronized keyword and the implementation class of Lock are pessimistic lock. Let's take a look at how pessimistic locks are implemented.
After thread A grabs the resource, thread B gets stuck and waits for thread A to release the resource.
When thread A releases the resource, thread B acquires the lock and starts to operate the resource. "pessimistic locks ensure that resources can only be operated by one thread at the same time.
Optimistic lock
In contrast to pessimistic locks, optimistic locks do not think that someone will change when accessing data (so it is optimistic), so it will not be locked when accessing resources, but go back to determine whether someone has modified the current data at the time of submission, we can use the version version number to implement it in the database. In Java we use CSA to implement it. Let's take a look at the execution process of the optimistic lock.
CAS
CAS (Compare And Swap) algorithm is a lock-free algorithm, which is a non-blocking atomic operation provided by Java. Synchronization under multithreading is realized without using locks. Atomic classes in concurrent packages (java.util.concurrent) use CAS to implement optimistic locking. CAS ensures newer atomicity through hardware. Unsafe provides a series of compareAndSwap* methods in JDK, so let's not delve into the Unsafe class here.
The process of CAS operation is to compare the data to be modified in memory with the expected value. If the two values are equal, change the value to the new value, otherwise, no operation will be done, that is, CAS needs three operation values:
An of the expected value
V in memory
B to be modified
To put it simply, CAS is an endless loop that determines whether the expected value is equal to the value in memory, makes changes if it is equal, continues the loop if it is not equal, and exits after successful execution.
The problem with CAS
Although CAS is very powerful, it also has some problems, such as ABA problems. For example, there is a shared variable X with a value of An in memory. At this time, a variable wants to modify the value of variable X. first, it will get the value of X. at this time, it will get A, and then use the CAS operation to change the X variable to B. This seems to be no problem, then if thread 2 changes the value of X to B and then the CAS operation executes to An after thread 1 acquires the variable X, thread 2 changes the value of X to B and then the CAS operation executes to A. although the value of the shared variable is A, this An is no longer the An obtained by thread 1.
This is the classic ABA problem. The ABA problem occurs because there is a circular transition between the state values of the variables, A can go from B to B and from A to A, but this problem will not happen if A to B, B to C.
Solution: add the AtomicStampedReference method after JDK1.5 to add a timestamp to each variable to avoid the ABA problem.
At the same time, CAS also has the problem of high loop overhead, because it loops until the expected equal memory modification is successful. At the same time, there is the problem that only one shared variable can be guaranteed atomicity, but the AtomicReference class is added after JDK1.5 to ensure atomicity between reference objects.
Use pessimistic and optimistic locks
Pessimistic locks can be implemented using the synchronized keyword, and optimistic locks can use the atomic classes provided under the union package.
Fair lock and unfair lock
Pessimistic lock and optimistic lock are mentioned above, now let's look at fair lock and unfair lock. There are also fairness and unfairness in the lock. Fair lock, as its name suggests, is fair, so if multiple threads apply for the lock at the same time, the thread will be placed in a queue, and the first thread in the queue can obtain the lock resources on a first-come-first-served basis. For example, when we were eating in the school canteen, at that time I remember that my classmates would hurry to line up in the canteen after school so that they could get meals as soon as possible, and no one would miss the meal in the process of queuing. At this time, the aunt in the canteen is fair and everyone can have a meal in line, and so is the thread. The unfair lock can be understood in this way. My classmate went to the canteen to wait in line for dinner, but someone jumped the queue, but the canteen aunt was unfair and directly beat the meal to the queue jumper but not to him. Is it unfair for you to be angry or not? it is not necessarily first-come-first-served to highlight the unfair lock. However, fair locking also has its drawbacks. When a thread acquires resources, other threads in the queue can only block. CPU's fair locking is much less efficient than unfair locking. Because CPU wakes up blocking threads is more expensive than unfair locks. Let's look at an example:
In Java, ReentrantLock provides the implementation of fair lock and unfair lock. Take a look at how ReentrantLock implements fair and unfair locks.
Use fair and unfair locks
ReentrantLock is an unfair lock by default. Let's take a look at an example of a fair lock:
Fair lock
Take a look at the output:
Output result
We can see that the output of the fair lock is on a first-come-first-served basis.
Let's take a look at an example of unfair locks:
An example of unfair locking
Output result:
Output result
We can see that if unfair locks are used, the final output is completely out of order, first-come-first-served.
So when using a fair lock, thread 1 acquires the lock and thread 2 suspends and waits for thread 1 to release the lock before thread 2 can acquire the lock. If another thread 3 wants to request a lock, if an unfair lock is used, then one of thread 2 and thread 3 will acquire the lock. In the case of fair lock, thread 3 can only hang first and wait for thread 2 to acquire the lock resource after it is released.
When to use fair lock and unfair lock
Use fair locks in scenarios where fair resources are needed, and try to use unfair locks if you don't need special fair treatment, because fair locks will incur performance overhead.
Exclusive lock and shared lock
What do you think of monopoly and sharing? the right exclusive lock is that only one thread can occupy the lock resource at a time, while other threads can only wait for the current thread to release the lock resource before they can acquire the lock again. The ReentrantLock just above is the exclusive lock, so isn't the exclusive lock pessimistic? Because after the pessimistic lock preempts the resource, it can only wait for other threads to be released before it can get the lock resource again. In fact, exactly speaking, exclusive lock is also pessimistic lock.
When talking about shared locks, shared locks are also optimistic locks, which relaxes the lock policy to allow multiple threads to acquire locks at the same time. ReadWriteLock is a typical shared lock in concurrent packages. It allows a resource to be accessed by multiple reads or by a write operation, but not both.
Spin lock
What is a spin lock? spin lock means that when a thread acquires a lock and the lock has been acquired by others, then the thread will not hang immediately, but will try to acquire lock resources again without giving up the right to use CPU. The default number is 10 times. You can use-XX: PreBlockSpinsh to set the number of times. If the spin lock takes too long to acquire the lock, it will cause subsequent threads to exhaust and release CPU resources. And spin locks are unfair.
Advantages
Spin lock will not make the thread state switch, always in the user mode, that is, the thread has always been active; will not make the thread into the blocking state, reducing unnecessary context switching, and the execution speed is fast.
Thank you for your reading, the above is the content of "detailed introduction of various locks in Java". After the study of this article, I believe you have a deeper understanding of the detailed introduction of various locks in Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.