Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Locking and unlocking process of Synchronized lightweight Lock

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "the locking and unlocking process of Synchronized lightweight locks". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Weight lock

In the last article, we introduced the usage of Synchronized and the principle of its implementation. We should now know that Synchronized is implemented through a monitor called a monitor lock inside the object. But the essence of the monitor lock depends on the Mutex Lock of the underlying operating system. The operating system needs to switch between threads, which requires a transition from user mode to core mentality, which is very expensive, and the transition between states takes a relatively long time, which is why Synchronized is inefficient. Therefore, this kind of lock which depends on the implementation of the operating system Mutex Lock is called "heavyweight lock". The core of all the optimizations made to Synchronized in JDK is to reduce the use of this heavy lock. After JDK1.6, in order to reduce the performance consumption and improve the performance caused by acquiring and releasing locks, "lightweight locks" and "biased locks" are introduced.

Second, lightweight lock

There are four kinds of lock states: no lock state, bias lock, lightweight lock, and heavy lock. With the competition of locks, locks can be upgraded from biased locks to lightweight locks, and then upgraded heavyweight locks (but lock upgrades are one-way, that is, they can only be upgraded from low to high, and there will be no lock degradation). Bias locks and lightweight locks are turned on by default in JDK 1.6. we can also disable bias locks through-XX:-UseBiasedLocking. The state of the lock is saved in the object's header file, taking the 32-bit JDK as an example:

"lightweight" is relative to traditional locks implemented using operating system mutexes. However, first of all, it needs to be emphasized that lightweight locks are not used to replace heavy locks, but are intended to reduce the performance consumption caused by the use of traditional heavyweight locks without multithreaded competition. Before explaining the execution process of lightweight locks, it is clear that lightweight locks adapt to scenarios where threads execute synchronous blocks alternately, and if there is a situation in which the same lock is accessed at the same time, it will cause the lightweight lock to expand into a heavy lock.

1. The locking process of lightweight lock

(1) when the code enters the synchronization block, if the lock state of the synchronization object is unlocked (the lock flag bit is "01", and whether the bias lock is "0"), the virtual machine will first establish a space called lock record (Lock Record) in the stack frame of the current thread, which is used to store the current Mark Word copy of the lock object, which is officially called Displaced Mark Word. At this point, the state of the thread stack and object header is shown in figure 2.1.

(2) copy the Mark Word in the object header to the lock record.

(3) after the copy is successful, the virtual machine will use the CAS operation to attempt to update the Mark Word of the object to the pointer to Lock Record, and point the owner pointer in Lock record to object mark word. If the update is successful, step (3) is performed, otherwise step (4) is performed.

(4) if the update action is successful, then the thread has the lock of the object, and the lock log bit of the object Mark Word is set to "00", which means that the object is in a lightweight locked state. At this time, the state of the thread stack and object header is shown in figure 2.2.

(5) if the update operation fails, the virtual machine will first check whether the Mark Word of the object points to the stack frame of the current thread. If it means that the current thread already has the lock of the object, it can go directly to the synchronization block to continue execution. Otherwise, if multiple threads compete for locks, the lightweight lock will expand to the heavyweight lock, and the state value of the lock flag will become "10". What is stored in Mark Word is the pointer to the heavyweight lock (mutex), and the thread waiting for the lock will also enter the blocking state. The current thread tries to use spin to acquire the lock, which is the process of using a loop to acquire the lock in order to prevent the thread from blocking.

Figure 2.1 lightweight lock stack and object state before CAS operation

Fig. 2.3 conversion diagram of the three

The picture is mainly a summary of the above content, if you have a better understanding of the above content, the picture should be easy to understand.

IV. Other optimizations

1. Adaptive spin (Adaptive Spinning): from the process of acquiring lightweight locks, we know that when threads fail to perform CAS operations in the process of acquiring lightweight locks, they need to spin to acquire heavy locks. The problem is that spinning consumes CPU, and if you don't get the lock all the time, the thread spins all the time, wasting CPU resources. The easiest way to solve this problem is to specify the number of spins, for example, let it cycle 10 times, and enter the blocking state if you haven't acquired the lock. But JDK takes a smarter approach-adaptive spin, which simply means that if the thread spins successfully, it will spin more next time, and if the spin fails, the number of spins will decrease.

2. Lock coarsening (Lock Coarsening): the concept of lock coarsening should be easier to understand, that is, lock and unlock operations that have been connected many times are combined into one, and multiple consecutive locks are extended into a larger lock. For example:

1 package com.paddx.test.string; 2 3 public class StringBufferTest {4 StringBuffer stringBuffer = new StringBuffer (); 5 6 public void append () {7 stringBuffer.append ("a"); 8 stringBuffer.append ("b"); 9 stringBuffer.append ("c"); 10} 11}

Here, each call to the stringBuffer.append method requires locking and unlocking. If the virtual machine detects a series of locking and unlocking operations on the same object, it will merge them into a larger range of locking and unlocking operations, that is, locking the first append method and unlocking it after the last append method ends.

3. Lock removal (Lock Elimination): lock removal is to delete unnecessary locking operations. According to the code escape technology, if it is determined that the data on the heap will not escape from the current thread, then the code can be considered thread-safe and does not need to be locked. Look at the following program:

1 package com.paddx.test.concurrent; 2 3 public class SynchronizedTest02 {4 5 public static void main (String [] args) {6 SynchronizedTest02 test02 = new SynchronizedTest02 (); 7 / start preheating 8 for (int I = 0; I

< 10000; i++) { 9 i++;10 }11 long start = System.currentTimeMillis();12 for (int i = 0; i < 100000000; i++) {13 test02.append("abc", "def");14 }15 System.out.println("Time=">

Although the append of StringBuffer is a synchronous method, the StringBuffer in this program is a local variable and will not escape from the method, so the process is thread-safe and the lock can be eliminated. Here is the result of my local execution: to minimize the impact of other factors, biased locks (- XX:-UseBiasedLocking) are disabled here. Through the above program, we can see that the performance has been greatly improved after eliminating the lock. Note: the results of execution may vary from version to version of JDK, and the version of JDK I use here is 1.6. 1: reduce lock holding time for example: lock a method, it is better to lock several lines of code that need to be synchronized in the method; 2: reduce the lock granularity for example: ConcurrentHashMap locks segment instead of the entire map to improve concurrency; 3: lock separation according to the nature of synchronous operation, the lock is divided into read lock and write lock, read locks are not mutually exclusive, improving concurrency. 5. Summary this article focuses on the optimization of Synchronized using lightweight locks and biased locks in JDk, but these two locks are not completely without shortcomings. For example, when the competition is relatively fierce, not only can not improve the efficiency, but will reduce the efficiency, because there is one more lock upgrade process, at this time you need to use-XX:-UseBiasedLocking to disable biased locks. The following is a comparison of these locks: lock advantages and disadvantages apply to scenarios where locking and unlocking do not require additional consumption, and there is only a nanosecond gap between locking and unlocking and performing asynchronous methods. If there is lock contention between threads, it will lead to additional consumption of lock revocation. Applies to scenarios where only one thread accesses the synchronous block. Lightweight lock contending threads do not block, which improves the response speed of the program. If a thread that never gets lock contention uses spin, it consumes CPU. Pursue response time. The execution speed of synchronous blocks is very fast. Heavy lock threads compete without spin and do not consume CPU. Threads are blocked and response time is slow. Pursue throughput. The execution speed of synchronous block is long. This is the content of "locking and unlocking process of Synchronized lightweight Lock". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report