


JAVA's ReadWriteLock interface and its implementation ReentrantReadWriteLock method
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:
1 2 3 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 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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 |
|
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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, the hasQueuedPredecessors method is called as follows:
1 2 3 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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
