In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
What is the process of Synchronized upgrade? aiming at this problem, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
In order to understand Synchronized, we should first be clear about bias locks, lightweight locks and heavyweight locks, and we need wait/wait (time) / notify/notifyAll in use. Let's introduce the flow and usage of Synchronized.
The upgrade process of Synchronized
(biased locks and lightweight locks introduced in Java SE 1.6 to reduce the performance consumption of acquiring and releasing locks)
The upgrade order of Synchronized is no lock-> bias lock-> lightweight lock-> heavy lock, which is irreversible.
Bias lock
When a thread accesses the synchronous code block and acquires the lock, the lock biased thread ID is stored in the lock record in the object header and stack frame. The biased lock is a reentrant lock. Later, when the thread enters and exits the synchronous code block, it does not need to spend CAS operations to lock and unlock. Instead, simply test whether there is a biased lock pointing to the current thread (the thread ID of the current thread) in the Mark Word of the object header. If the test is successful, it indicates that the thread has acquired the lock. If the test fails, you need to test again whether the biased lock identity in Mark Word is set to 1 (indicating that it is currently biased lock). If the biased lock ID is 1, CAS is used for lock acquisition. If the lock ID is not 1, try to use CAS to point the biased lock of the object header to the current thread. The above two CAS acquire lock operations If the CAS operation is successful, the biased lock is acquired, and the failure indicates that there is a lock competition and a lock revocation operation is required.
Lock revocation
The biased lock uses a mechanism that waits for competition to release the lock, so when other threads try to compete for the biased lock, the thread that holds the biased lock releases the lock. The revocation of the biased lock needs to wait for the thread with the biased lock to reach the global safe point (no bytecode is executing at this point in time). It will first pause the thread with the biased lock, and then check whether the thread holding the biased lock is alive. If the thread is not active, the object header of the locked object is set to unlocked, if the thread is still alive The stack with a biased lock will be executed * * (to determine whether it is necessary to hold a lock), traverse the lock record of the biased object to check its usage, and upgrade the biased lock to a lightweight lock if it is still needed. If there is no need to hold a biased lock, the lock object will be restored to an unlocked state, and finally the paused thread will be awakened.
Lightweight lock
Before the thread executes the synchronization block, JVM first creates a space to store the lock record in the stack frame of the current thread, and copies the Mark Word in the object header to the lock record, officially known as Displaced Mark Word. The thread then attempts to use CAS to replace the Mark Word in the object header with a pointer to the lock record. If successful, the current thread acquires the lock, if it fails, indicating that other threads are competing for the lock, the current thread attempts to use spin to acquire the lock, and if the number of spins exceeds the set number, it is upgraded to a heavy-level lock, or when a thread is holding a lock, one is spinning, and there is a third visit, the lightweight lock is upgraded to a heavy-level lock, and the heavyweight lock blocks all threads except the thread that owns the lock. Prevent CPU from idling.
Lightweight lock unlock
When lightweight unlocking, the atomic CAS operation is used to replace the Displaced Mark Word back to the object header, which, if successful, indicates that no competition occurs. If it fails, it indicates that there is competition for the current lock, and the lock expands to a heavy lock.
* * for example: * * the T1 thread holds the lock and the T2 thread spins, but the maximum number of T2 thread spins has passed, then the spin fails, the lock is upgraded to a heavy lock, and the T2 thread is blocked. At this time, T1 executes the synchronous code block and carries out lightweight locking and unlocking, but at this time, the flag bit in Mark Word has changed from 00 (bias lock) to 10 (intermediate level lock). Unlocking will cause CAS failure. T 1 unlocks (releases the monitor, releases the lock) and wakes up the thread T 2.
Weight lock
Synchronized is an unfair lock. When a thread enters the blocking queue in Synchronized, the waiting thread will first try to acquire the lock, and if it cannot get it, it will enter the blocking queue, which is obviously unfair to the thread that has already entered the queue.
Advantages and disadvantages of locking scenarios tend to lock plus unlock does not require too much resource consumption, compared with the non-synchronous method is only a nanosecond gap if there is competition, there will be additional lock revocation operations applicable to scenarios with only one thread access, lightweight lock competitive threads will not block, spin, and reduce online text switching. If you do not get the lock all the time, it will consume cpu resources to pursue response time, and most of the synchronization code blocks are computed. There is no advantage in executing fast scenario heavyweight locks, thread blocking response time, slow synchronization code blocks, long execution time scenarios using flowcharts.
Synchronized method
1: Synchronized is the built-in lock of java, which is also an exclusive lock and an unfair lock. The exclusive lock means that after the current thread acquires the lock, other threads will block and suspend. The unfair lock will be tried first and then unlocked when the thread removes the lock.
2: how does Synchronized guarantee atomicity? Because the memory semantics of entering the Synchronized block is to clear the 'working memory' used in the Synchronized block, so that when using shared variables, it will be directly stored in the main memory and copied to your working memory, and the calculated 'shared variables' in the working memory will be updated to the main memory when exiting the Synchronized statement block.
3: when Synchronized locks are acquired, they are all 'object locks' rather than 'code block locks' (locks are all objects or classes, not certain methods), so Synchronized is reentrant. After acquiring the object lock, you can enter directly without having to acquire the locks of other methods of the object.
4: if Synchronized is used on static, it means a class lock. No matter how many objects are created, it is not feasible.
Difference
Wait differs from sleep in that wait releases the lock, but sleep does not release the lock, and sleep causes thread blocking to hang.
The wait/wait (timeout) / notify/notifyAll method can be used only after the lock has been acquired.
explain
Wait: thread waits.
Wait (time): the thread waits and continues execution if the time exceeds the set time.
Notify: randomly wakes up a waiting thread.
NotifyAll: wakes up all waiting threads.
Code demonstration / * * @ Auther: concurrenncy * @ Date: 2019-03-25 16:43 * @ Company: pay along the way * @ maill: lan_tao@suixingpay.com * @ Description: wait differs from sleep in that wait releases locks, but sleep does not, and sleep causes thread blocking to suspend * / public class WaitAndNotifyTest {private static Object obj = new Object () Public static void main (String [] args) {/ / create thread thread1 Thread thread1 = new Thread (new Runnable () {@ Override public void run () {try {System.out.println (Thread.currentThread ()) .getName () + "begin wait...") Synchronized (obj) {obj.wait ();} System.out.println (Thread.currentThread (). GetName () + "end wait...") } catch (Exception e) {e.printStackTrace ()}, "thread1") / / create thread thread2 Thread thread2 = new Thread (new Runnable () {@ Override public void run () {try {System.out.println (Thread.currentThread (). GetName () + "begin wait...") Synchronized (obj) {obj.wait ();} System.out.println (Thread.currentThread (). GetName () + "end wait...") } catch (Exception e) {e.printStackTrace ();}, "thread2"); / / start thread1.start (); thread2.start () Try {/ / sleep one second Thread.sleep (1000L);} catch (InterruptedException e) {e.printStackTrace () } / / if the thread calling notify does not acquire an object lock, it throws a java.lang.IllegalMonitorStateException exception synchronized (obj) {/ / wakes up one of the threads calling the wait method using obj (random) obj.notify () when calling notify / / Wake up all threads using obj to call the wait method obj.notifyAll () } this is the end of the answer to the question about the Synchronized upgrade process. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
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.