Home Java javaTutorial JAVA's ReadWriteLock interface and its implementation ReentrantReadWriteLock method

JAVA's ReadWriteLock interface and its implementation ReentrantReadWriteLock method

Jun 30, 2017 am 10:32 AM
java readwritelock accomplish

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1264
29
C# Tutorial
1237
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles