In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces what locks are in the Java concurrency scenario, which can be used for reference by interested friends. I hope you can learn a lot after reading this article.
01. Optimistic lock vs pessimistic lock
Optimistic lock and pessimistic lock are concepts in a broad sense, which reflect the different perspectives of thread synchronization. There are practical applications of this concept in both Java and database.
1. Optimistic lock
As the name implies, it is very optimistic. Every time you go to get the data, you think that others will not modify it, so you will not lock it. But when you update it, you will judge whether others have updated the data during this period. You can use mechanisms such as version number.
Optimistic locking is suitable for multi-read applications. Optimistic locking is realized by using lock-free programming in Java, the most common algorithm is CAS algorithm, and the incremental operation in Java atomic class is realized by CAS spin.
CAS, whose full name is Compare And Swap (compare and Exchange), is a lock-free algorithm. Variable synchronization between multithreads is achieved without using locks (no threads are blocked). The atomic classes in the java.util.concurrent package implement optimistic locking through CAS.
To put it simply, the CAS algorithm has three operands:
The memory value V that needs to be read and written.
The value A for comparison.
The new value B to write.
If and only if the expected value An and the memory value V are the same, modify the memory value V to B, otherwise return V. This is an optimistic locking idea, which believes that no other thread will modify it before it is modified, while Synchronized is a pessimistic lock, which thinks that other threads must modify it before it is modified, and pessimistic locking is very inefficient.
two。 Pessimistic lock
Always assume that in the worst-case scenario, 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, so that others will block until it gets the lock.
Many of these locking mechanisms are used in traditional MySQL relational databases, such as row locks, table locks, read locks, write locks and so on. For details, please refer to: Ali P8 architect: the characteristics and applications of MySQL row lock, table lock, pessimistic lock and optimistic lock.
For example, the implementation of the synchronous synchronized keyword for Java mentioned above is a typical pessimistic lock.
3. In short:
Pessimistic locks are suitable for scenarios with many write operations. Adding a lock first can ensure that the data is correct during the write operation.
Optimistic lock is suitable for scenarios with many read operations, and the characteristic of unlocking can greatly improve the performance of read operations.
02. Fair lock vs unfair lock
1. Fair lock
It is fair that in a concurrent environment, each thread will first check the waiting queue maintained by the lock when acquiring the lock. If it is empty, or if the current thread is * of the waiting queue, it will own the lock, otherwise it will join the waiting queue and will get itself from the queue in accordance with the rules of FIFO.
The advantage of fair locking is that the thread waiting for the lock will not starve to death. The disadvantage is that the overall throughput efficiency is relatively low. All threads except * * threads in the waiting queue will block, and the overhead of CPU waking up blocked threads is higher than that of unfair locks.
two。 Unfair lock
Just try to occupy the lock directly, and if the attempt fails, use a method similar to the fair lock.
The advantage of unfair locking is that it can reduce the overhead of arousing threads, and the overall throughput efficiency is high, because threads have the chance to acquire locks directly without blocking, and CPU does not have to wake up all threads. The disadvantage is that threads in the waiting queue may starve to death or wait a long time to acquire the lock.
3. Typical applications:
ReentrantLock in the java jdk concurrent package can specify the boolean type of the constructor to create fair and unfair locks (default). For example, fair locks can be implemented using new ReentrantLock (true).
03. Exclusive vs shared lock
1. Exclusive lock
Means that the lock can only be held by one thread at a time.
two。 Shared lock
Means that the lock can be held by multiple threads.
3. Compare
For Java ReentrantLock, it is an exclusive lock. But for another implementation class of Lock, ReadWriteLock, its read lock is a shared lock and its write lock is exclusive.
The shared lock of the read lock ensures that concurrent reads are very efficient, and the processes of reading and writing are mutually exclusive.
Exclusive lock and shared lock are also realized through AQS, through the implementation of different methods to achieve exclusive or shared.
4.AQS
Abstract queue Synchronizer (AbstractQueuedSynchronizer, referred to as AQS) is the basic framework for building locks or other synchronization components. It uses an integer volatile variable (named state) to maintain the synchronization state and queues the resource acquisition thread through the built-in FIFO queue.
The implementation structure of the concurrent package is shown in the figure above. Basic classes such as AQS, non-blocking data structures, and atomic variable classes are all based on volatile variable read / write and CAS implementations, while high-level classes such as Lock, synchronizer, blocking queue, Executor, and concurrent containers are based on base class implementations.
04. Sectional lock
Segmented lock is actually a kind of lock design, not a specific kind of lock. For ConcurrentHashMap, the realization of concurrency is to achieve efficient concurrent operation in the form of segmented lock.
Let's talk about the meaning and design idea of segmented lock in ConcurrentHashMap. The segmented lock in ConcurrentHashMap is called Segment, which is similar to the structure of HashMap (the implementation of HashMap in JDK7 and JDK8), that is, there is an internal Entry array, and each element in the array is a linked list; at the same time, it is also a ReentrantLock (Segment inherits ReentrantLock).
When the put element is needed, instead of locking the entire hashmap, we first know which segment it is going to put through hashcode, and then lock the segment, so when multithreaded put, as long as it is not placed in a segment, real parallel insertion is achieved.
However, when you count size, you need to get all the segmented locks when you get the global information of hashmap.
The purpose of the segmented lock is to refine the granularity of the lock, and when the operation does not need to update the entire array, the locking operation is performed on only one item in the array.
Thank you for reading this article carefully. I hope the article "what locks are there in Java concurrency scenarios" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.