The locks in the locks package of the Java concurrency package have basically been introduced. ReentrantLock is the key. After clearly understanding the operating mechanism of the synchronizer AQS, it will actually be easier to analyze these locks. Much more, this chapter focuses on another important lock - ReentrantReadWriteLock read-write lock.
ReentrantLock is an exclusive lock, which means that only one thread can acquire the lock. But what if the scenario is that the thread only performs read operations? In this way, ReentrantLock is not very suitable. The reading thread does not need to ensure the security of its thread. Any thread can acquire the lock. Only in this way can performance and efficiency be guaranteed as much as possible. ReentrantReadWriteLock is such a lock. It is divided into a read lock and a write lock. N read operation threads can obtain the write lock, but only 1 write operation thread can obtain the write lock. Then it is foreseeable that the write lock will The lock is a shared lock (shared mode in AQS), and the read lock is an exclusive lock (exclusive mode in AQS). First, let’s look at the interface class of the read-write lock:
1 public interface ReadWriteLock { 2 Lock readLock(); //获取读锁3 Lock writeLock(); //获取写锁4 }
You can see that the ReadWriteLock interface only defines two methods, the method of acquiring the read lock and the method of acquiring the write lock. The following is the implementation class of ReadWriteLock - ReentrantReadWriteLock.
Similar to ReentrantLock, ReentrantReadWriteLock also implements synchronizer AQS through an internal class Sync. It also implements fair locks and unfair locks by implementing Sync. This idea is similar to ReentrantLock. How are the read locks and write locks obtained in the ReadWriteLock interface implemented?
//ReentrantReadWriteLockprivate final ReentrantReadWriteLock.ReadLock readerLock;private final ReentrantReadWriteLock.WriteLock writerLock;final Sync sync;public ReentrantReadWriteLock(){this(false); //默认非公平锁}public ReentrantReadWriteLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); //锁类型(公平/非公平)readerLock = new ReadLock(this); //构造读锁writerLock = new WriteLock(this); //构造写锁} ……public ReentrantReadWriteLock.WriteLock writeLock0{return writerLock;}public ReentrantReadWriteLock.ReadLock readLock0{return ReaderLock;}
//ReentrantReadWriteLock$ReadLockpublic static class ReadLock implements Lock {protected ReadLock(ReentrantReadwritLock lock) { sync = lock.sync; //最后还是通过Sync内部类实现锁 } …… //它实现的是Lock接口,其余的实现可以和ReentrantLock作对比,获取锁、释放锁等等}
//ReentrantReadWriteLock$WriteLockpublic static class WriteLock implemnts Lock {protected WriteLock(ReentrantReadWriteLock lock) { sync = lock.sync; } …… //它实现的是Lock接口,其余的实现可以和ReentrantLock作对比,获取锁、释放锁等等}
The above is a general introduction to ReentrantReadWriteLock. You can see that there are several internal classes inside it. In fact, there are two locks in the read-write lock - ReadLock and WriteLock. These two locks implement the Self-Lock interface and can be compared with ReentrantLock. The internal implementation of these two locks is through Sync, which is the synchronizer AQS. Implemented, this can also be compared with Sync in ReentrantLock.
Looking back at AQS, there are two important data structures inside it - one is the synchronization queue and the other is the synchronization state. This synchronization state is applied to the read-write lock, which is the read-write state, but there is only one state in AQS. The integer represents the synchronization status. In the read-write lock, there are two synchronization statuses of reading and writing that need to be recorded. Therefore, the read-write lock processes the state integer in AQS. It is an int variable with a total of 4 bytes and 32 bits. Then the read and write states can occupy 16 bits each - the high 16 bits represent reading. The lower 16 bits indicate writing.
Now there is a question. If the value of state is 5, the binary is (000000000000000000000000000000101). How to quickly determine the respective states of reading and writing? This requires the use of displacement operations. The calculation method is: write state state & 0x0000FFFF, read state state >>> 16. Increasing the write state by 1 is equal to state + 1, and increasing the read state by 1 is equal to state + (1 << 16). For shift operations, please refer to "<<, >>, >>>Shift Operations".
According to our previous experience, we can know that AQS has already set up the algorithm skeleton for acquiring locks, and only needs to be implemented by subclasses tryAcquire (exclusive lock), so we only need to check tryAcquire.
1 //ReentrantReadWriteLock$Sync 2 protected final boolean tryAcquire(int acquires) { 3 Thread current = Thread.currentThread; 4 int c = getState(); //获取state状态 5 int w = exclusiveCount(c); //获取写状态,即 state & 0x00001111 6 if (c != 0) { //存在同步状态(读或写),作下一步判断 7 if (w == 0 || current != getExclusiveOwnerThread()) //写状态为0,但同步状态不为0表示有读状态,此时获取锁失败,或者当前已经有其他写线程获取了锁此时也获取锁失败 8 return false; 9 if (w + exclusiveCount(acquire) > MAX_COUNT) //锁重入是否超过限制10 throw new Error(“Maxium lock count exceeded”);11 setState(c + acquire); //记录锁状态12 return true;13 }14 if (writerShouldBlock() || !compareAndSetState(c, c + acquires))15 return false; //writerShouldBlock对于非公平锁总是返回false,对于公平锁则判断同步队列中是否有前驱节点16 setExclusiveOwnerThread(current);17 return true;18 }
The above is the status acquisition of the write lock. What is difficult to understand is the writerShouldBlock method. This method is described above. Unfair locks directly return false, while for fair locks, hasQueuedPredecessors is called. The method is as follows:
1 //ReentrantReadWriteLock$FairSync2 final boolean writerShouldBlock() {3 return hasQueuedPredecessors();4 }
What is the reason? This comes back to the difference between unfair locks and fair locks. To briefly review, please refer to "5.Lock Interface and Its Implementation ReentrantLock" for details. For unfair locks, each time a thread acquires a lock, it will first force the lock acquisition operation regardless of whether there are threads in the synchronization queue. When the acquisition cannot be obtained, the thread will be constructed to the end of the queue; for fair locks, as long as the synchronization queue If there are threads in the queue, the lock will not be acquired, but the thread structure will be added to the end of the queue. So back to the acquisition of write status, in the tryAcquire method, it was found that no thread holds the lock, but at this time, corresponding operations will be performed according to the different locks. For unfair locks - lock grabbing, for fair locks - synchronization queue There are threads in the thread, no lock grabbing, and added to the end of the queue.
The release process of write lock is basically similar to the release process of ReentrantLock. After all, they are all exclusive locks. Each release reduces the write status until it is reduced to 0, which means the write lock has been completely released.
In the same way, based on our previous experience, we can know that AQS has already set up the algorithm skeleton for acquiring locks. The subclass implements tryAcquireShared (shared lock), so we only need to check tryAcquireShared. We know that for locks in shared mode, it can be acquired by multiple threads at the same time. Now the problem comes. The T1 thread acquires the lock, and the synchronization state is state=1. At this time, T2 also acquires the lock, state=2, and then the T1 thread Re-entry state=3, which means that the read state is the sum of the number of read locks for all threads, and the number of times each thread has acquired the read lock can only be saved in ThreadLock and maintained by the thread itself, so some things need to be done here. Complex processing, the source code is a bit long, but the complexity lies in the fact that each thread saves the number of times it acquires a read lock. For details, refer to tryAcquireShared in the source code. Read it carefully and combine it with the above analysis of write lock acquisition. It is not difficult to understand.
What is noteworthy about the release of read locks is the number of lock acquisitions maintained by itself, and the reduction of state state through shift operations - (1 << 16).
The above is the detailed content of ReadWriteLock interface and its implementation ReentrantReadWriteLock. For more information, please follow other related articles on the PHP Chinese website!