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
synchronized
It 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!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
