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/03 Report--
Next, please follow the editor to study!
First, why use locks?
Lock-is to solve the problem of dirty reading and data inconsistency caused by concurrent operations.
Second, the basic principle of lock implementation
2.1 、 volatile
The Java programming language allows threads to access shared variables, and to ensure that shared variables are updated accurately and consistently, threads should ensure that the variable is obtained separately through exclusive locks. The Java language provides volatile, which is more convenient than locks in some cases.
Volatile ensures the "visibility" of shared variables in multiprocessor development. Visibility means that when one thread modifies a shared variable, another thread can read the modified value.
Conclusion: if the volatile variable modifier is used properly, it is cheaper to use and execute than synchronized because it does not cause thread context switching and scheduling.
2.2 、 synchronized
Synchronized implements synchronization through the locking mechanism.
Let's take a look at the basics of synchronization using synchronized: every object in Java can be used as a lock.
It is embodied in the following three forms.
For normal synchronization methods, the lock is the current instance object.
For static synchronization methods, the lock is the Class object of the current class.
For synchronous method blocks, locks are the objects configured in Synchonized parentheses.
When a thread tries to access a synchronous block of code, it must first get the lock, and the lock must be released when it exits or throws an exception.
2.2.1 implementation principle of synchronized
Synchronized is based on Monitor to achieve synchronization.
Monitor supports synchronization between threads in two ways:
Mutually exclusive execution
Collaboration
1. Java uses object locks (using synchronized to obtain object locks) to ensure mutually exclusive execution of threads working on a shared dataset.
2. Use the notify/notifyAll/wait method to coordinate the work between different threads.
3. Both Class and Object are associated with a Monitor.
The working Mechanism of Monitor
The thread enters the synchronization method.
In order to continue executing the critical section code, the thread must acquire the Monitor lock. If the lock is successfully acquired, it becomes the owner of the monitor object. The monitor object belongs to only one active thread (The Owner) at any one time
The thread that owns the monitor object can call wait () to enter the waiting set (Wait Set) while releasing the monitor lock and entering the waiting state.
Other threads call the notify () / notifyAll () interface to wake up threads in the waiting set, which need to reacquire the monitor lock before executing code after wait ().
After the execution of the synchronization method, the thread exits the critical area and releases the monitor lock.
Reference document: https://www.ibm.com/developerworks/cn/java/j-lo-synchronized
2.2.2 concrete implementation of synchronized
The main contents are as follows: 1. The synchronization code block is explicitly implemented by monitorenter and monitorexit instructions.
2. The synchronization method is implicitly implemented using ACC_SYNCHRONIZED tags.
Take a look at the specific implementation through an example:
The compiled bytecode of javap is as follows:
Monitorenter
Each object has a monitor, and a monitor can only be owned by one thread. When a thread executes the monitorenter instruction, it attempts to get the monitor of the corresponding object. The acquisition rules are as follows:
If the number of entries to monitor is 0, the thread can enter monitor and set the number of monitor entries to 1, which is the owner of the monitor.
If the current thread already owns the monitor and just re-enters, the number of entries into the monitor is incremented by 1, so the lock implemented by the synchronized keyword is a reentrant lock.
If the monitor is already owned by another thread, the current thread enters a blocking state until the number of entries to the monitor is 0, and then retries to get the monitor.
Monitorexit
Only the thread that owns the monitor of the corresponding object can execute the monitorexit instruction. Each time the instruction monitor is executed, the number of entries minus 1, the current thread releases monitor when the number of entries is 0, and other blocked threads can try to get the monitor.
2.2.3 where the lock is stored
The lock tag is stored in the Mark Word of the Java object header.
Java object header length
32-bit JVM Mark Word architecture
32-bit JVM Mark Word state change
64-bit JVM Mark Word structure
2.2.3 Lock Optimization of synchronized
In order to reduce the performance consumption caused by acquiring and releasing locks, JavaSE1.6 introduces "biased locks" and "lightweight locks".
In JavaSE1.6, there are four states of lock, from low to high: no lock state, partial lock state, lightweight lock state, and heavy lock state, which will escalate gradually with the competition.
Locks can be upgraded but cannot be degraded, which means that biased locks cannot be degraded to biased locks after upgrading to lightweight locks. This lock upgrade strategy can not be degraded in order to improve the efficiency of acquiring and releasing locks.
Bias lock:
In the case of no lock competition, in order to reduce the resource overhead of lock competition, biased lock is introduced.
Lightweight locks:
Lightweight locks are adapted to scenarios where threads execute synchronous blocks alternately.
Lock coarsening (Lock Coarsening): that is, reducing unnecessary unlock,lock operations linked together, extending multiple consecutive locks into a larger range of locks.
Lock removal (Lock Elimination): lock removal refers to the removal of locks that require synchronization on some code but are detected to be impossible to compete for shared data when the virtual machine just-in-time compiler is running.
Adaptive spin (Adaptive Spinning): adaptive means that the spin time is no longer fixed, but is determined by the spin time of the previous time on the same lock and the state of the lock owner. If, on the same lock object, spin wait has just successfully acquired the lock, and the thread holding the lock is running, the virtual machine will think that the spin is likely to succeed again, which in turn will allow the spin wait to last relatively longer, such as 100 cycles. On the other hand, if spin is rarely successfully acquired for a lock, the spin process may be omitted when acquiring the lock in the future, so as to avoid wasting processor resources.
2.2.4 comparison of advantages and disadvantages of locks
2.3 、 CAS
CAS, in Java concurrent applications, usually refers to CompareAndSwap or CompareAndSet, that is, compare and exchange.
1. CAS is an atomic operation that compares the value of a memory location and only changes the value of this memory location to a new value when it is equal, ensuring that the new value is always calculated based on the latest information. If other threads modify this value during this period, CAS fails. CAS returns whether it is successful or the original value of the memory location is used to determine whether the CAS is successful.
2. The CAS operation in JVM is realized by using the CMPXCHG instruction provided by the processor.
Advantages:
The system overhead is small when there is little competition.
Disadvantages:
The cycle time is long and the cost is high.
The problem follows the ABA.
Only one atomic operation of a shared variable is guaranteed.
Third, the lock implementation in Java
3.1queue Synchronizer (AQS)
Queue Synchronizer AbstractQueuedSynchronizer (hereinafter referred to as Synchronizer) is the basic framework for building locks or other synchronization components.
3.1.1. It uses an int member variable to represent the synchronization status.
3.1.2, through the built-in FIFO two-way queue to complete the queuing work of acquiring lock threads.
The synchronizer contains applications of two node types, one pointing to the head node and the other pointing to the tail node. The thread that does not acquire the lock creates the node thread-safe (compareAndSetTail) tail of the queue. The synchronization queue follows the FIFO, and the first node is the node that successfully obtains the synchronization status.
The thread that does not acquire the lock creates a node and sets it to the tail node. As shown in the following figure:
When the thread of the first node releases the lock, it will wake up the successor node. The subsequent node will set itself as the first node when the lock is successfully acquired. As shown in the following figure:
3.1.3, exclusive / shared lock acquisition
Exclusive: one and only one thread can acquire the lock, such as ReentrantLock
Shared: locks can be acquired by multiple threads at the same time, such as CountDownLatch
Exclusive type
Each node spins to see if its previous node is a Header node, and if so, tries to acquire the lock.
Exclusive lock acquisition process:
Shared:
The difference between shared and exclusive:
Shared lock acquisition process:
Use cases of locks
4.1. the implementation principle and use of ConcurrentHashMap
ConcurrentHashMap class diagram
ConcurrentHashMap data structure
Conclusion: the lock segmentation technique used by ConcurrentHashMap. First, the data is stored in segments, and then each piece of data is assigned a lock. When a thread occupies the lock to access one segment of data, the data of other segments can also be accessed by other threads.
At this point, the study of "the implementation principle and example usage of locks 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.