search
HomeJavajavaTutorialWhat is the upgrade process of synchronized locks in Java?

What is a synchronized lock? A lock is actually an object, any one can be used. All objects in Java are locks. In other words, all objects in Java can become locks.
This time we are mainly talking about the routine of synchronized lock upgrade

synchronizedIt will go through four stages: Lock-free state, biased lock, lightweight lock, weight Level lock is ordered from the least resource consuming and the highest performance to the most resource consuming and the worst performance.

Lock Principle

Let’s first look at why these status locks are called locks and what their mutual exclusion principle is.

Biased lock

When a thread reaches the synchronization code block and tries to obtain the lock object, it will check the MarkWord in the object header. Thread ID, if there is no ID here, save your own and get the lock. If there is, check whether it is the current thread. If not, CAS will try to change it. If it is, the lock resource has been obtained.

Here is a detailed description of the logic that CAS attempts to modify: it will check the status of the thread holding the biased lock. First traverse all the surviving threads of the current JVM. If can find the biased thread, it means that the biased thread is still alive , and it will be checked at this time Is the thread executing the code in the synchronized code block? If so, it will be upgraded to a lightweight lock and continue to compete for CAS locks. Therefore, after adding a biased lock, only one thread can obtain the lock and execute the code in the synchronized code block at the same time.

Lightweight Lock

Check whether the Lock Record pointer in the MarkWord in the object header points to the virtual machine stack of the current thread. If yes, use the lock to execute the business. If not, perform CAS and try to modify it. If modifications are unsuccessful several times, upgrade to a heavyweight lock.

Heavyweight lock

Check the ObjectMonitor pointed to in the MarkWord in the object header, check whether the owner is the current thread, if not, throw Queue it in EntryList in ObjectMonitor, and suspend the thread, waiting to be awakened.

Lock upgrade

No lock

Under normal circumstances, a new new object is temporarily in the lock-free state . Because bias locks are delayed by default, there is no bias lock in the first 4 seconds of starting the JVM. However, if the bias lock delay setting is turned off, an anonymous bias lock will be added to the new object. That is to say, this object wants to find a thread to add a bias lock, but cannot find one, which is called anonymous bias. The stored thread IDs are a bunch of 0000's, and there's no address information whatsoever.

We can turn off the biased lock delay through the following configuration.

//关闭偏向锁延迟的指令
-XX:BiasedLockingStartuoDelay=0

Biased lock

When a thread comes to obtain this lock resource, it will be successfully acquired at this time, and it will become a biased lock, biased lock storage thread ID.

When biased lock is upgraded, biased lock revocation will be triggered. Biased lock revocation needs to wait until a safe point, such as GC, The cost of bias lock revocation is too high, so by default, bias lock delay will be performed at the beginning. If there are multiple threads competing directly, the bias lock will be skipped and directly become a lightweight lock.

Let’s talk about the process of bias lock cancellation in detail. Why is the cost high? When a thread obtains a biased lock, it will point the thread id in the Mark Work of the lock object header to itself. When another thread comes to compete for the lock and the lock is upgraded, it willPause the thread that obtained the biased lock before, then clear the thread id in Mark Work, add a lightweight lock, and thenrestore the paused The thread continues executing . This is why you wait until a safe point before performing lock escalation, because the thread is paused.

Common safety points:

  • When executing GC

  • Before the method returns

  • After calling a method

  • The location where the exception is thrown

  • The end of a loop

Lightweight lock

When competition among multiple threads occurs, it will be upgraded to Lightweight lock. The effect of lightweight lock isbased on CAS tries to acquire the lock resource , where adaptive spin lock will be used. The number of spins this time is determined based on the success or failure of the last CAS and the time spent.

Lightweight locks are suitable for scenarios where the competition is not very fierce. One thread gets the lock, executes the synchronization code block, and the process is completed quickly. Another thread tries once or twice to get the lock, and then executes it again, which will not make a thread wait for a long time.

Heavyweight lock

If it reaches a heavyweight lock, there is nothing to say. If a thread holds the lock, other those who want to take the lock will hang up and wait for the lock. After release, they are awakened in sequence.

Lock coarsening & lock elimination

Lock coarsening/lock expansion

Lock expansion is an optimization that JIT helps us do when compiling Java files. It will reduce locks The number of acquisitions and releases. for example:

while(){
   synchronized(){
      // 多次的获取和释放,成本太高,会被优化为下面这种
   }
}
synchronized(){
   while(){
       //  拿到锁后执行循环,只加锁和释放一次
   }
}

锁消除

锁消除则是在一个加锁的同步代码块中,没有任何共享资源,也不存在锁竞争的情况,JIT编译时,就直接将锁的指令优化掉。 比如

synchronized(){
   int a = 1;
   a++;
   //操作局部变量的逻辑
}

The above is the detailed content of What is the upgrade process of synchronized locks in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Apr 19, 2025 pm 08:06 PM

Questions about a curve integral This article will answer a curve integral question. The questioner had a question about the standard answer to a sample question...

What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?Apr 19, 2025 pm 08:03 PM

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Apr 19, 2025 pm 07:57 PM

Why can't the main class be found after copying and pasting the package in IDEA? Using IntelliJIDEA...

Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Apr 19, 2025 pm 07:54 PM

State synchronization between Java multi-interface calls: How to ensure that interface A is called after it is executed? In Java development, you often encounter multiple calls...

In Java programming, how to stop subsequent code execution when student ID is repeated?In Java programming, how to stop subsequent code execution when student ID is repeated?Apr 19, 2025 pm 07:51 PM

How to stop subsequent code execution when ID is repeated in Java programming. When learning Java programming, you often encounter such a requirement: when a certain condition is met,...

Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Apr 19, 2025 pm 07:48 PM

In-depth discussion of final consistency: In the distributed system of application scenarios and implementation methods, ensuring data consistency has always been a major challenge for developers. This article...

After the Spring Boot service is running for a period of time, how to troubleshoot?After the Spring Boot service is running for a period of time, how to troubleshoot?Apr 19, 2025 pm 07:45 PM

The troubleshooting idea of ​​SSH connection failure after SpringBoot service has been running for a period of time has recently encountered a problem: a Spring...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.