Java Memory Model-lock, java model
Lock release-obtain the established happens before relationship
Locks are the most important synchronization mechanism in java concurrent programming. In addition to mutex execution in the critical section, the lock release thread can send messages to the thread that obtains the same lock. The following is an example code of lock release-obtaining:
class MonitorExample { int a = 0; public synchronized void writer() { //1 a++; //2 } //3 public synchronized void reader() { //4 int i = a; //5 …… } //6}
Assume that thread A executes the writer () method, and thread B then executes the reader () method. According to the happens before rule, the happens before relationship contained in this process can be divided into two types:
The figure of the above happens before relationship is as follows:
In, each arrow links two nodes, representing a happens before relationship. The black arrow indicates the procedural order rules, the orange arrow indicates the monitor lock rules, and the blue arrow indicates the happens before guarantee provided after these rules are combined.
After thread A releases the lock, thread B obtains the same lock. In, 2 happens before 5. Therefore, all visible shared variables of thread A before releasing the lock will immediately become visible to thread B after thread B acquires the same lock.
Memory semantics of lock release and Acquisition
When the thread releases the lock, JMM refreshes the shared variables in the local memory corresponding to the thread to the main memory. The above MonitorExample program is used as an example. After thread A releases the lock, the data sharing status is as follows:
When the thread gets the lock, JMM will invalidate the local memory corresponding to the thread. So that the code in the critical section protected by the monitor must read the shared variable from the main memory. The following shows the lock acquisition status:
Compared with the memory semantics obtained from lock release and volatile write-read, we can see that the lock release and volatile write share the same memory semantics; the lock acquisition has the same memory semantics as volatile reads.
The following summarizes the memory semantics of lock release and lock acquisition:
- Thread A releases A lock. In essence, thread A sends A message to A thread that is going to obtain the lock (thread A modifies the shared variable.
- Thread B acquires a lock. In essence, thread B receives the message sent by a previous thread (which modifies the shared variable before the lock is released.
- Thread A releases the lock, and then thread B obtains the lock. This process is essentially because thread A sends A message to thread B through the main memory.
Implementation of lock memory Semantics
This article uses the source code of ReentrantLock to analyze the specific implementation mechanism of lock memory semantics.
See the following sample code:
Class ReentrantLockExample {int a = 0; ReentrantLock lock = new ReentrantLock (); public void writer () {lock. lock (); // obtain the lock try {a ++;} finally {lock. unlock (); // release lock} public void reader () {lock. lock (); // get the lock try {int I = ;...... } Finally {lock. unlock (); // release the lock }}}
In ReentrantLock, call the lock () method to obtain the lock, and call the unlock () method to release the lock.
The implementation of ReentrantLock depends on the java synchronization framework AbstractQueuedSynchronizer (AQS ). AQS uses an integer volatile variable (named state) to maintain the synchronization state. We will see that this volatile variable is the key to implementing the memory semantics of ReentrantLock. The following is the ReentrantLock class diagram (only the sections related to this Article are drawn ):
ReentrantLock is divided into fair locks and unfair locks. We first analyze fair locks.
When a fair lock is used, the call track of the lock () method is as follows:
The source code of the method is as follows:
Protected final boolean tryAcquire (int acquires) {final Thread current = Thread. currentThread (); int c = getState (); // get the start of the lock, first read the volatile variable state if (c = 0) {if (isFirst (current) & compareAndSetState (0, acquires) {setExclusiveOwnerThread (current); return true ;}} else if (current = getExclusiveOwnerThread () {int nextc = c + acquires; if (nextc <0) throw new Error ("Maximum lock count exceeded"); setState (nextc); return true ;}return false ;}
From the source code above, we can see that the locking method first reads the volatile variable state.
When using the fair lock, the call track of the unlock method unlock () is as follows:
Release the lock in step 1. The source code of this method is as follows:
Protected final boolean tryRelease (int releases) {int c = getState ()-releases; if (Thread. currentThread ()! = GetExclusiveOwnerThread () throw new IllegalMonitorStateException (); boolean free = false; if (c = 0) {free = true; setExclusiveOwnerThread (null);} setState (c ); // At the end of the lock release, write the volatile variable state return free ;}
From the source code above, we can see that the volatile variable state is written at the end of the lock release.
The fair lock writes the volatile variable state at the end of the lock release; read the volatile variable first when obtaining the lock. According to the happens-before rule of volatile, the thread releasing the lock is visible to the shared variable before the volatile variable is written, after the lock obtaining thread reads the same volatile variable, it immediately becomes visible to the lock obtaining thread.
Now we analyze the implementation of the memory semantics of unfair locks.
The release of unfair locks is exactly the same as that of fair locks, so here we only analyze the acquisition of unfair locks.
When an unfair lock is used, the call track of the lock () method is as follows:
The source code of the method is as follows:
protected final boolean compareAndSetState(int expect, int update) { return unsafe.compareAndSwapInt(this, stateOffset, expect, update);}
This method updates the state variable Through atomic operations. This document calls java's compareAndSet () method for short as CAS. JDK describes this method as follows: if the current status value is equal to the expected value, the synchronization status is set to the specified update value in an atomic mode. This operation has volatile read and write memory semantics.
Here we analyze from the compiler and processor perspectives how CAS simultaneously has the memory semantics of volatile read and volatile write.
As mentioned above, the compiler will not resort any memory operations after volatile read and volatile read; the compiler will not resort any memory operations before volatile write and volatile write. Combining these two conditions means that in order to simultaneously implement the memory semantics of volatile read and volatile write, the compiler cannot re-Sort any memory operations before and after CAS and CAS.
Next we will analyze how CAS has both volatile read and volatile write memory semantics in common intel x86 processors.
The following is the source code of the compareAndSwapInt () method of the sun. misc. Unsafe class:
public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
We can see that this is a local method call. The C ++ code called by this local method in openjdk is: unsafe. cpp, atomic. cpp and atomicwindowsx86.inline. hpp. The final implementation of this local method is in the following position of openjdk:openjdk-7-fcs-src-b147-27jun2011\openjdk\hotspot\src\oscpu\windowsx86\vm\ atomicwindowsx86.inline.hpp(Corresponding to the windows operating system and X86 processor ). The following is the source code snippet corresponding to the intel x86 processor:
// Adding a lock prefix to an instruction on MP machine// VC++ doesn't like the lock prefix to be on a single line// so we can't insert a label after the lock prefix.// By emitting a lock prefix, we can define a label after it.#define LOCK_IF_MP(mp) __asm cmp mp, 0 \ __asm je L0 \ __asm _emit 0xF0 \ __asm L0:inline jint Atomic::cmpxchg (jint exchange_value, volatile jint* dest, jint compare_value) { // alternative for InterlockedCompareExchange int mp = os::is_MP(); __asm { mov edx, dest mov ecx, exchange_value mov eax, compare_value LOCK_IF_MP(mp) cmpxchg dword ptr [edx], ecx }}
As shown in the source code above, the program determines whether to add a lock prefix for the cmpxchg command based on the type of the current processor. If the program runs on a multi-processor, add the lock prefix (lock cmpxchg) to the cmpxchg command ). Conversely, if the program runs on a single processor, the lock prefix is omitted (the single processor itself maintains the order consistency within the single processor without the memory barrier effect provided by the lock prefix ).
The intel manual describes the lock prefix as follows:
The memory barrier effects of the above 2nd points and 3rd points are sufficient to implement both volatile read and volatile write memory semantics.
After the above analysis, we can finally understand why the JDK documentation says that CAS has both volatile read and volatile write memory semantics.
Now we will summarize the memory semantics of the fair lock and the non-fair lock:
- When a fair lock and a non-fair lock are released, the volatile variable state must be written.
- When a fair lock is obtained, the volatile variable is read first.
- When an unfair lock is obtained, CAS is used to update the volatile variable. This operation also has the memory semantics written by volatile and volatile.
From the ReentrantLock analysis in this article, we can see that there are at least two methods to implement the lock release-acquired memory semantics:
Concurrent package implementation
Since java's CAS both have the memory semantics of volatile read and volatile write, the communication between Java threads now has the following four methods:
Java CAS uses efficient machine-level atomic commands provided on modern processors. These atomic commands perform read-Modify-write operations on the memory in an atomic manner, this is the key to implementing synchronization in a multi-processor. (In essence, it is an asynchronous equivalent machine that supports atomic read-write commands, therefore, any modern multi-processor will support some atomic commands that can perform atomic read-write operations on the memory ). At the same time, the reading/writing of volatile variables and CAS can implement communication between threads. The integration of these features forms the cornerstone of the entire concurrent package. If we carefully analyze the source code implementation of the concurrent package, we will find a universal implementation mode:
AQS, non-blocking data structures and atomic variable classes (java. util. concurrent. classes in the atomic Package). These basic classes in the concurrent package are implemented using this mode, and the high-level classes in the concurrent package depend on these basic classes. The concurrent package is implemented as follows: