Image
Known Synchronize keywords are common solutions for solving concurrency problems, with the following three ways to use them:
- The normal method is synchronized, and the lock is the current object.
- Synchronizes a static method, which locks the current
Class object.
- The synchronization block, which is the
{} object in the lock.
Implementation principle:
JVMis to Monitor synchronize the methods and synchronization blocks by entering and exiting the object Monitor ().
The implementation is to add an instruction monitor.enter to the exit method and the exception inserted after the synchronization method call after compilation monitor.exit .
Its essence is to obtain an object monitor ( Monitor ), and this acquisition process is exclusive to achieve the same time only a thread access.
For a thread that does not acquire a lock, it will block to the method entrance until the thread acquires the lock monitor.exit before attempting to continue acquiring the lock.
The flowchart is as follows:
Image
To demonstrate through a piece of code:
public static void main(String[] args) { synchronized (Synchronize.class){ System.out.println("Synchronize"); } }
Use javap -c Synchronize to view specific information after compilation.
PublicClassCom.Crossoverjie.Synchronize.Synchronize {public Com.crossoverjie.synchronize.Synchronize (); Code:0:aload_01:invokespecial #1Method java/lang/object. " <init> ":() V4:ReturnPublicStaticvoid Main (java.lang.string[]); Code:0:LDC #2Class Com/crossoverjie/synchronize/synchronize2:dup3:astore_1 * *4:monitorenter**5:getstatic #3Field Java/lang/system.out:ljava/io/printstream;8:LDC #4String Synchronize10:invokevirtual #5 //Method java/ IO/PRINTSTREAM.PRINTLN: (ljava/lang/string;) V 13:aload_1 **14 : monitorexit** 15: goto 23 18:astore_2 19:aload_1 20:monitorexit Span class= "Hljs-number" >21:aload_2 22:athrow 23: return Exception table:from to target type 5 15 Span class= "Hljs-number" >18 any 18 21 18 any}
Can be seen in the synchronization block of the inlet and outlet respectively havemonitorenter,monitorexit
Instructions.
Lock optimization
synchronizeMany of these are called weight locks, in which the JDK1.6 synchronize various optimizations are carried out in order to reduce the acquisition and release of the lock brought by the consumption introduced 偏向锁 and 轻量锁 .
Light weight Lock
When the code enters the synchronization block, if the synchronization object is unlocked, the current thread creates a lock record () region in the stack frame Lock Record , copies the object header of the lock object Mark Word to the lock record, and then attempts to use the pointer that CAS will be Mark Word updated to point to the lock record.
If the update succeeds , the current thread obtains the lock.
If the update fails JVM , it first checks whether the lock object Mark Word points to the lock record of the current thread.
If yes, the current thread has a lock on the lock object and can go directly to the synchronization block.
No, it means that other threads have preempted the lock, and if there are multiple threads competing for a lock at the same time, the light-weight lock expands to a weight lock .
Unlock
The unlocking process for a lightweight lock is also CAS implemented using the lock record to replace the lock object Mark Word . If the substitution succeeds, the entire synchronization operation completes, and the failure indicates that another thread is trying to acquire the lock, and the suspended thread is awakened (it is now inflated to 重量锁 )
The reason why lightweight locks can improve performance is that most locks do not compete during the entire synchronization cycle, so using CAS less mutex is more expensive than using mutexes. But if the lock competition is fierce, the light-weight lock has not only the exclusive overhead, but also CAS the overhead, even slower than the weight lock.
Biased lock
To further reduce the cost of acquiring locks, JDK1.6 a biased lock is introduced.
The characteristic of a biased lock is that there is no multi-threaded competition for locks and that locks should be obtained multiple times by a single thread.
When a thread accesses a synchronization block, it uses the update of the CAS thread ID to the lock object Mark Word , and if the update succeeds, it obtains a biased lock and does not need to acquire the lock again each time it enters the synchronization block associated with the object lock.
Release lock
When another thread acquires the lock, the thread that holds the biased lock releases the lock, waits for the global security point when it is released (no bytecode runs), and pauses the thread that has the biased lock, depending on whether the lock object is currently locked to determine if the object header is Mark Word set to no lock or to a lightweight lock state.
Lightweight locks can improve program performance with synchronous but no competition, but if the majority of locks in the program are competitive, then the bias lock does not play a big role. You can use -XX:-userBiasedLocking=false to turn off the biased lock and enter the light lock by default.
Other optimized adaptive spin
When used CAS , if the operation fails, the CAS spin is tried again. Since spin is a resource-intensive CPU , it can be wasted if long-term spin is needed CPU . JDK1.6Added adaptive spin:
If a lock spin is rarely successfully obtained, the next time the spin is reduced.
Extra
Recently in summarizing some Java-related knowledge points, interested friends can be maintained together.
Address: Https://github.com/crossoverJie/Java-Interview
Crossoverjie
Links: https://www.jianshu.com/p/2ba154f275ea
Java multi-thread synchronize keyword principle