Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement a bias lock in Java

Shulou Source: shulou.com Published: 2022-06-02 08:34:19 10月01日 Update

Today, I will talk to you about how to achieve a bias lock in Java. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Bias lock, like lightweight lock, is also a new lock in JDK 1.6. its purpose is to solve the problem of removing synchronization statements when there is no competition, and further improve the performance of the program. In the previous article, we learned that lightweight locks use CAS operations to remove synchronization when there are numerous data competitions. Then in the biased lock, the entire synchronization is removed in case of numerous data competition, and even the CAS operation does not need to be done. The actual nature of a biased lock is to favor the thread that acquires it first. when this thread is executing, if the lock is not acquired by another thread, the thread holding the biased lock will not need to be synchronized all the time. Let's take a look at what happens to Mark Word when a thread acquires a biased lock.

When the thread first acquires the lock, the virtual machine changes the flag bit in the Mark Word to 01, which is biased mode. At the same time, the thread that acquired the lock is recorded in the Mark Word of the object with the CAS operation. If the CAS operation is successful, the virtual machine does not perform any synchronization each time the thread holding the bias lock executes the synchronization block. In other words, bytecode instructions related to synchronization will not be called. When another thread tries to acquire the lock, the bias pattern ends. The following figure shows the changes in information such as object Mark Word when biased locks and lightweight locks are converted.

After reading the above, do you have any further understanding of how to implement a biased lock in Java? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Thread synchronization content data lightweight lightweight competition object that is in the pattern into one change success below in that is code information at the same time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Microsoft Xiaomi vpn Shulou Information