Home >Java >javaTutorial >Java keyword synchronized principle and lock status example analysis
Spin lock: means that when a thread acquires the lock, if the lock has been acquired by other threads, then the thread will wait in a loop , and then continuously determine whether the lock can be successfully acquired, and the loop will not exit until the lock is acquired.
Optimistic locking: Assuming there is no conflict, if the data is found to be inconsistent with the previously obtained data when modifying the data, read the latest data and retry the modification.
Pessimistic lock: Assuming that a concurrency conflict will occur, synchronize all data-related operations, and start locking from the time the data is read.
Exclusive lock (write): Add a write lock to the resource. The thread can modify the resource, but other threads cannot lock it again (single write).
Shared lock (read): After adding a read lock to a resource, it can only be read but not modified. Other threads can only add read locks and cannot add write locks (multiple). Just think of it as a Semaphore (semaphore).
Reentrant lock & non-reentrant lock: After a thread obtains a lock, it can freely enter other code synchronized by the same lock.
Fair lock & unfair lock: The order of competing for locks, if it is first come, first served, is fair. That is to say, it is a fair lock if the order of grabbing the lock and the order of grabbing the lock are guaranteed to be the same.
Features: reentrant, exclusive, pessimistic lock.
Lock-related optimization:
Lock elimination: The parameters to enable lock elimination are -XX: DoEscapeAnalysis
, -XX: EliminateLocks
.
Lock coarsening: JDK has optimized lock coarsening, but we can optimize it from the code level.
/** * 锁消除示例,JIT即时编译,进行了锁消除 * @author 刘亚楼 * @date 2020/1/16 */ public class LockEliminationExample { /** * StringBuilder线程不安全,StringBuffer用了synchronized关键字,是线程安全的 * 针对下面这种单线程加锁、解锁操作,JIT会进行优化,进行锁消除 */ public static void eliminateLock() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("a"); stringBuffer.append("b"); stringBuffer.append("c"); stringBuffer.append("a"); stringBuffer.append("b"); stringBuffer.append("c"); stringBuffer.append("a"); stringBuffer.append("b"); stringBuffer.append("c"); } }
/** * 锁粗化示例 * @author 刘亚楼 * @date 2020/1/16 */ public class LockCoarseningExample { /** * 针对下面这种无意义的加锁操作,JIT会进行优化,对变量i的所有操作放到一个同步代码块里 */ public static void lockCoarsening() { int i = 0; synchronized (LockCoarseningExample.class) { i++; } synchronized (LockCoarseningExample.class) { i--; } synchronized (LockCoarseningExample.class) { i++; } synchronized (LockCoarseningExample.class) { i++; i--; i++; } } }
Note: The difference between lock elimination and lock coarsening is lock elimination It is optimized for repeated adding and unlocking of a single thread, and ultimately no lock exists. Lock coarsening is not only for single threads, but ultimately there are locks.
First of all, the object in the heap consists of object header, instance data and alignment padding.
The object header contains two parts of information. The first part is used to store the runtime data of the object itself, such as hash code, GC generation age, lock status flag, lock held by the thread, bias lock id, etc. This part of the data is officially called "Mark Word".
The other part of the object header is the type pointer, which is the pointer of the object to its class metadata. The virtual machine uses this pointer to determine which class the object is an instance of.
The lock implemented by synchronized is achieved by changing the "Mark Word" of the object header.
"Mard Word" is 32-bit and 64-bit in 32-bit and 64-bit virtual machines (compressed pointers are not turned on) respectively. The 32-bit virtual machine "Mark Word" is as follows:
When lock-free becomes lightweight lock, multiple threads will read the lock-free status mark word content of the object header of the object, and then perform cas
operations to modify it. The expected value is lock-free Status mark word content. The new value is the lightweight lock status mark word content. If the modification is successful, Lock record address
points to the Lock Record
of the thread that successfully acquired the lock.
The demonstration process is as follows:
##(2) Lightweight lock→ Heavyweight lockDue to the thread that failed to acquire the lock successfully It will spin. Long-term spin will consume CPU resources. Therefore, if it spins for a certain number of times, the lock will be upgraded from a lightweight lock to a heavyweight lock. Heavyweight locks are implemented through object monitors, which include entryList (lock pool), owner (lock holder), waitSet (wait set), etc. When upgrading to a heavyweight lock, the content of the object header mark word is the monitor address (object monitor address), pointing to the object monitor. The demonstration process is as follows: Note: The thread that fails to grab the lock will enter the entryList (lock pool). After calling the wait method, the thread will enter the waitSet( Wait set), the thread in waitSet will re-enter entryList after being awakened. (3) About bias lockNo unlocking after locking, for single threadThe so-called bias is eccentricity, after single thread locks, it will no longer unlock, which reduces Lock→Business processing→Release lock→Lock operation process. After JDK6, the biased lock optimization has been enabled by default. The biased lock can be disabled through the JVM parameter-XX:-UseBiasedLocking. If the biased lock is enabled, only one thread will grab the lock. You can Obtain bias lock.
The bias mark is useful for the first time, but becomes useless after contention occurs.
The essence of biased lock is that it is lock-free. If no multi-threads compete for locks, the JVM considers it to be a single thread and no synchronization is required.
Note: In order to reduce the work of the JVM, synchronization is implemented by many operations at the bottom of the JVM. If there is no contention, there is no need to perform synchronization operations.
If the bias lock is not turned on, the lock-free state will be upgraded to a lightweight lock first, and the lightweight lock will be upgraded to a heavyweight if it is selected to a certain extent. Lock.
If the biased lock is turned on, there are two situations:
When the lock is not occupied, it will be upgraded to no lock, and then it will be upgraded to lightweight The lock is upgraded from a lightweight lock to a heavyweight lock.
When the lock is occupied, it will be upgraded to a lightweight lock, and then upgraded from a lightweight lock to a heavyweight lock.
The above is the detailed content of Java keyword synchronized principle and lock status example analysis. For more information, please follow other related articles on the PHP Chinese website!