In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to upgrade synchronized locks in JAVA, the quality of the article content is high, so Xiaobian shares it with you as a reference, I hope you have a certain understanding of related knowledge after reading this article.
1. Basic understanding of synchronization
Scenario: Synchronized is a synchronization keyword, in some multithreaded scenarios, if not synchronized will lead to data insecurity, and Synchronized keyword is used for code synchronization. Under what circumstances will the data be unsafe, two conditions must be met: one is data sharing (critical resources), and the other is multiple threads accessing and changing the data simultaneously.
Synchronized is called heavyweight locking in multithreaded concurrent programming. However, as Java SE 1.6 makes various optimizations for synchronization, it is not so heavy in some cases. Java SE 1.6 introduces biased locks and lightweight locks to reduce the performance cost of acquiring and releasing locks.
1.1 synchronized There are three ways to lock
1.1.1. Decorate instance method, apply lock to current instance, obtain lock of current instance before entering synchronization code
1.1.2. Static method, acting on the current class object lock, before entering the synchronization code to obtain the lock of the current class object
1.1.3. Modifies a block of code that specifies a locked object, locks the given object, and acquires the lock of the given object before entering the code base at the same step.
1.2 Mark word
Mark word records information about objects and locks. When an object is regarded as a synchronous lock by synchronized keyword, a series of operations around this lock are related to Mark word. Mark Word is 32 bits long in a 32-bit virtual machine and 64 bits long in a 64-bit virtual machine. The data stored in Mark Word will change with the change of the lock flag bit. Mark Word may change to store the following 5 situations.
32-bit
lock base
1.2.1. First, every object in Java derives from the Object class, and every Java Object has a native C++ object inside the JVM called oop/oopDesc.
1.2.2. When a thread acquires a lock, it actually acquires a monitor object. Monitor can be considered a synchronous object. All Java objects naturally carry monitors.
2. Upgrade of synchronized lock
When analyzing markword, bias lock, lightweight lock and heavyweight lock are mentioned.
After JDK 1.6, some optimizations were made. In order to reduce the performance overhead caused by acquiring and releasing locks, the concept of biased locks and lightweight locks was introduced. Therefore, you will find that in synchronized, there are four states of locks: no lock, biased lock, lightweight lock, heavyweight lock; the state of the lock is continuously upgraded from low to high according to the intensity of competition.
2.1 Basic Principles of Bias Lock
As mentioned earlier, in most cases, not only is there no multi-thread competition for locks, but locks are always acquired by the same thread multiple times, and the concept of biased locks is introduced to make it cheaper for threads to acquire locks. What do you mean by bias lock? When a thread accesses a block of code with a synchronization lock, it stores the ID of the current thread in the object header, and subsequent threads enter and exit the block of code with a synchronization lock without locking and releasing the lock again. Instead, it directly compares whether the object header stores a biased lock pointing to the current thread. If equal means the lock is biased towards the current thread, there is no need to try to acquire the lock again.
2.1.1 Biased lock acquisition and revocation logic
1. Firstly, the Markword of the lock object is obtained, and whether it is in the deflectable state is judged. (biased_lock=1 and ThreadId is empty)
2. If it is deflectable, write the ID of the current thread to MarkWord via CAS operation a) If cas succeeds, markword will become like this. b) If cas fails, it means that another thread has obtained the biased lock. This situation indicates that there is competition for the current lock. It is necessary to revoke the thread that has obtained the biased lock and upgrade the lock it holds to a lightweight lock (this operation needs to wait until the global safety point, that is, no thread is executing byte code).
3. If it is biased state, check whether the ThreadID stored in markword is equal to the ThreadID of the current thread a) If it is equal, it is not necessary to obtain the lock again, and the synchronization code block can be directly executed b) If it is not equal, it means that the current lock is biased to other threads, and it is necessary to revoke the biased lock and upgrade to a lightweight lock.
2.1.2 Revocation of biased locks
Deviating biased locks does not restore objects to lock-free biased states (because biased locks do not have the concept of lock release), but in the process of acquiring biased locks, when cas fails, i.e., there is thread contention, the biased lock object is directly upgraded to a state where lightweight locks are added.
When revoking a thread that originally held a biased lock, the thread that originally acquired the biased lock has two situations:
2.1.2.1. If the thread that originally obtained the biased lock has exited the critical section, that is, the execution of the code block at the same step is completed, then at this time, the object header will be set to the unlocked state and the thread competing for the lock can be re-biased based on CAS.
2.1.2.2. If the synchronization code block of the thread that originally obtained the biased lock has not been executed and is in the critical section, the thread that originally obtained the biased lock will be upgraded to a lightweight lock and continue to execute the synchronization code block. In our application development, in most cases, there must be more than two threads competing, so if you open the biased lock, it will increase the resource consumption of acquiring the lock. Therefore, you can set the bias lock to open or close through the jvm parameter UseBiasedLocking
2.2 Basic principles of lightweight locks
Locking and unlocking logic for lightweight locks
2.2.1 When a lock is upgraded to a lightweight lock, the Markword of the object changes accordingly.
Upgrade to Lightweight Lock:
2.2.1.1. Thread creates lock record LockRecord in its own stack frame.
2.2.1.2. Copy MarkWord from the lock object's object header to the thread's newly created lock record.
2.2.1.3. Point the Owner pointer in the lock record to the lock object.
2.2.1.4. Replace MarkWord for the lock object's object header with a pointer to the lock record.
2.2.2 Spinlock
Lightweight locks use spin locks during locking
Spinning means that when another thread competes for the lock, the thread loops around waiting in place, rather than blocking the thread until the thread that acquired the lock releases the lock, and the thread can immediately acquire the lock.
Note that when the lock loops in place, it consumes cpu, which is equivalent to executing a for loop with nothing.
Therefore, lightweight locks are useful in situations where synchronized blocks of code execute quickly, so that threads can acquire locks after waiting in place for a short time. The use of spin locks, in fact, also has a certain probability background, in most of the same step code block execution time is very short. So it is possible to improve lock performance by looping through seemingly unobjectionable loops. However, spin must be controlled conditionally, otherwise if a thread takes a long time to execute synchronous code blocks, then the thread's constant loop will consume CPU resources. By default, the number of spins is 10, which can be modified by preBlockSpin
After JDK 1.6, adaptive spin locking was introduced, which means that the number of spins is not fixed, but depends on the time of the previous spin on the same lock and the state of the lock owner. If spin wait has just succeeded in acquiring a lock on the same lock object, and the thread holding the lock is running, the VM assumes that spin is likely to succeed again, and it allows spin wait to persist longer.
If spin is rarely successfully acquired for a lock, then later attempts to acquire the lock will probably omit the spin process and block the thread directly, avoiding wasting processor resources.
2.2.3 Unlocking lightweight locks
The lock release logic of lightweight lock is actually the reverse logic of obtaining lock, replacing LockRecord in thread stack frame back to MarkWord of lock object through CAS operation. If it succeeds, it means there is no competition. If it fails, it indicates that there is competition for the current lock, and the lightweight lock expands to a heavyweight lock.
After adding the synchronization code block, you will see a monitorenter and monitorexit in the bytecode.
Every JAVA object is associated with a monitor, which can be understood as a lock. When a thread wants to execute a synchronized method or code block, the thread must first obtain the monitor corresponding to the synchronized object.
2.3- Basic principles of heavyweight locks
When lightweight locks inflate to heavyweight locks, it means threads can only be suspended and blocked waiting to be awakened.
monitorenter means to get an object monitor. monitorexit means to release the ownership of the monitor, so that other blocked threads can try to obtain this monitor. The monitor depends on the operating system's Mutex Lock (mutex lock) to implement. After the thread is blocked, it enters the kernel (Linux) scheduling state, which causes the system to switch back and forth between user mode and kernel mode, seriously affecting the lock performance.
About how to upgrade JAVA synchronized lock to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.
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.