Get to know synchronized and download it by yourself.
Synchronized ensures both atomicity and memory visibility. It is a thread synchronization method and a java Implementation of the lock mechanism. The implementation of synchronized is based on the JVM underlying layer. The JVM is implemented based on monitor, and the implementation of monitor depends on the implementation of the operating system mutex.
Semantics
Synchronized has two meanings:
Mutex ensures that all object state changes are invisible to other threads before the thread exits. It can be seen that when the thread enters the synchronous code block, the final state of the object state changes in the previous thread can be seen.
Thread security and Synchronization
Thread Security indicates that in a multi-threaded environment, no threads access Shared data at the same time.
Thread Synchronization is a serialized action of the thread callback class and instance field variables and other shared resources. It ensures that only one thread can access resources at a time. For example, there is only one last train ticket for the Spring Festival train ticket, and both A and B need to grab this train ticket. How can this problem be solved to prevent overselling? Protect resources and queue A and B to buy train tickets.
Thread security is a property, and thread synchronization is a method.
Command
The synchronized synchronization code block is implemented through the monitorenter and monitorexit commands, while the synchronized synchronization method is based on the ACC_SYCHRONIZED flag. The JVM checks this flag when the synchronization method is called. Monitorenter indicates the beginning of the critical section. When the thread executes the monitorenter command, it will try to obtain the ownership of the monitor corresponding to the object. monitorexit indicates the end of the critical section. When the thread executes the monitorexit command, the ownership of the monitor corresponding to the object will be released.
1 public class SynchronizedMethod {2 public synchronized void methodA() {3 System.out.println("MethodA start");4 5 }6 }
Pass this codejavap -cDecompilation: Focus on the 3rd and 13th lines after compilation.
1 Compiled from "SynchronizedTest.java" 2 public class com.memory.SynchronizedTest { 3 public com.memory.SynchronizedTest(); 4 Code: 5 0: aload_0 6 1: invokespecial #1 // Method java/lang/Object."<init>":()V 7 4: return 8 9 public void methodA();10 Code:11 0: aload_0 12 1: dup 13 2: astore_1 14 3: monitorenter 15 4: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;16 7: ldc #3 // String MethodA start17 9: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V18 12: aload_1 19 13: monitorexit 20 14: goto 2221 17: astore_2 22 18: aload_1 23 19: monitorexit 24 20: aload_2 25 21: athrow 26 22: return 27 Exception table:28 from to target type29 4 14 17 any30 17 20 17 any31 }
Lock type
Java synchronized lock upgrade
In JDK1.6, bias locks, lightweight locks, and heavyweight locks are introduced for synchronized optimization. The lock upgrade process is in the single direction. Only the upgrade from low to high is allowed, and the downgrade is not allowed.
Heavyweight Lock refers to the process of handing over control of the program running, suspending the thread, and the operating system is responsible for inter-Thread Scheduling and thread blocking and execution. In this way, frequent switching of the thread running status, thread suspension and awakening consume a large amount of system resources, resulting in low performance.
Lightweight Locking is relative to a heavyweight lock. In synchronized implementation, the spin method is used to replace thread switching by CPU spin wait, the competing thread will not be blocked to avoid the CPU load caused by blocking and wake-up. The spin method has advantages and disadvantages. When the lock takes a short time, the lock can be obtained after a small number of spin waits. However, when the lock takes a long time, spin will waste a lot of CPU resources in vain. Therefore, the number of spin times must be limited. If the spin fails, the lock will be immediately upgraded to a heavyweight lock, which is called lock expansion.
The literal meaning of Biased Locking is that the lock is private and tends to be the last accessed thread. In his essay QRL-OpLocks-BiasedLocking, Hotspot authors explain that in most cases there is no multi-thread competition for shared resources, and it is always obtained multiple times by the same thread, considering that the CAS (Compare-And-Swap) command causes a high CPU latency when obtaining the Java Monitor, a biased lock is introduced to lower the cost of locking the thread.
Lock mark position
In a 64-bit virtual machine, does the Mark field contain HashCode (hashcode that stores the HashCode value of the 31bits object), GC Generational Age (Generational GC Age, 4 bits, therefore, the maximum age of generation is 15), which is biased towards thread ID and lock mark.
The synchronized lock has four states: unlocked, biased, lightweight, and heavyweight locks, which correspond to different fields in Mark Word.
Mark Word in different levels of java synchronized locks
I'm Ge Yifan and hope it will be useful to you.
Reference