Home > Java > javaTutorial > body text

JAVA's ReadWriteLock interface and its implementation ReentrantReadWriteLock method

怪我咯
Release: 2017-06-30 10:32:38
Original
1322 people have browsed it

The following editor will bring you an article about the ReadWriteLock interface and its implementation ReentrantReadWriteLock method. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

The locks in the locks package of the Java concurrent package have basically been introduced. ReentrantLock is the key. After clearly understanding the operating mechanism of the synchronizer AQS , in fact, it will be much easier to analyze these locks. 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 one 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:

public interface ReadWriteLock { 
  Lock readLock();  //获取读锁
  Lock writeLock();  //获取写锁
 }
Copy after login

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 the synchronizer AQS through an internal class Sync. It also implements Sync to implement fair locks and unfair locks. This idea is similar to ReentrantLock. How are the read locks and write locks obtained in the ReadWriteLock interface implemented?

//ReentrantReadWriteLock
private 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;}
Copy after login
//ReentrantReadWriteLock$ReadLock
public static class ReadLock implements Lock {
 protected ReadLock(ReentrantReadwritLock lock) {
  sync = lock.sync;  //最后还是通过Sync内部类实现锁
  }
 …… //它实现的是Lock接口,其余的实现可以和ReentrantLock作对比,获取锁、释放锁等等
}
Copy after login
//ReentrantReadWriteLock$WriteLock
public static class WriteLock implemnts Lock {
 protected WriteLock(ReentrantReadWriteLock lock) {
  sync = lock.sync;
  }
…… //它实现的是Lock接口,其余的实现可以和ReentrantLock作对比,获取锁、释放锁等等
}
Copy after login


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 Lock interface and can be compared with ReentrantLock. The internal implementation of these two locks is implemented through Sync, which is the synchronizer AQS. This can also be compared with Sync in ReentrantLock. Compared.
Looking back at AQS, there are two important data structures inside it - one is the synchronization queue , and the other is the synchronization status . This synchronization status is applied to the read-write lock. That is, the read and write status, but there is only one state integer in AQS to represent 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 I have 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 bit shift operations, please refer to "<<, >>, >>> Shift Operations".

Acquisition and release of write locks

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.

//ReentrantReadWriteLock$Sync
protected final boolean tryAcquire(int acquires) {
 Thread current = Thread.currentThread;
 int c = getState(); //获取state状态
 int w = exclusiveCount(c); //获取写状态,即 state & 0x00001111
 if (c != 0) { //存在同步状态(读或写),作下一步判断
  if (w == 0 || current != getExclusiveOwnerThread())  //写状态为0,但同步状态不为0表示有读状态,此时获取锁失败,或者当前已经有其他写线程获取了锁此时也获取锁失败
   return false;
  if (w + exclusiveCount(acquire) > MAX_COUNT) //锁重入是否超过限制
   throw new Error(“Maxium lock count exceeded”);
  setState(c + acquire); //记录锁状态
  return true;
  }
  if (writerShouldBlock() || !compareAndSetState(c, c + acquires))
   return false;  //writerShouldBlock对于非公平锁总是返回false,对于公平锁则判断同步队列中是否有前驱节点
  setExclusiveOwnerThread(current);
  return true;
}
Copy after login

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, the hasQueuedPredecessors method is called as follows:

 //ReentrantReadWriteLock$FairSync
 final boolean writerShouldBlock() {
  return hasQueuedPredecessors();
 }
Copy after login

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.

Acquisition and release of read lock

Similarly, based on our previous experience, we can know that AQS has already set up the algorithm skeleton for acquiring locks. Only subclasses need to implement 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 JAVA's ReadWriteLock interface and its implementation ReentrantReadWriteLock method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!