In the previous article, we have Condition This explicit conditional queue mechanism is disassembled.

You already know:

  • Lock Not only synchronized "Another Writing"
  • Condition not just wait()/notify() simple replica
  • What the explicit lock system really brings is a more controllable locking, waiting and awakening mechanism
  • When thread collaboration begins to become complicated, Lock + Condition Often clearer than the built-in monitor model

But at this point, many people will continue to pursue a very practical question:

Since ReentrantLock It is already very easy to use, why does Java still provide ReadWriteLock?

And the name looks a bit abstract at first time:

  • What is "read-write lock"?
  • Why are read locks and write locks separated?
  • Can't an ordinary Mutex protect both read and write at the same time?
  • When can "read more and write less" really rely on read-write lock to speed up, when will it be slower?
  • ReentrantReadWriteLock How do you use it, and what can go wrong?

Behind these questions, they are essentially asking:

If many threads read a shared resource and only a few modify it, why make every thread wait in the same line?

This article will explain this.

I would like to focus on 6 questions:

  1. ReadWriteLock what problem to solve
  2. What is allowed and what is not allowed to read locks and write locks respectively
  3. ReentrantReadWriteLock what is the basic usage of
  4. Why is it more valuable in the "read more and less" scenario
  5. What are the meanings of lock downgrade and lock upgrade, and why be careful
  6. In real development, when to use it and when not to abuse

You can read this article thoroughly, and then learn it later:

  • StampedLock
  • Segmentation control ideas in concurrent containers
  • Typical concurrent designs such as cache, configuration center, local index, etc.

will be much smoother.


First, the conclusion: ReadWriteLock The core purpose is not to "make the lock more complicated", but to "make the read operation not to be blocked by meaninglessly"

When many people come into contact with Read-Write Lock for the first time, they will feel like they are stacked on a normal lock with another layer of rules.

But the problem it really solves is actually quite simple:

If multiple threads just read shared data and are not modified, they usually do not have real conflicts with each other.

The problem with ordinary Mutex is:

  • Whether you read or write
  • as long as the critical section
  • All other threads have to wait

This means:

  • a thread read configuration
  • The other thread is just read the configuration
  • As a result, the two still have to queue in series

From the "data security" point of view, this is of course true.

But from the perspective of "concurrency efficiency", it is often too conservative.

Therefore, the core idea of Read-Write Lock is to split the access into two categories:

  • Read operation: View only, do not modify
  • Write operation: will update the shared data

Then allow:

  • Multiple read threads enter at the same time
  • Write thread exclusively enter
  • It is forbidden to enter the concurrent entry of other read and write threads when writing

One sentence to understand:

Reading can be concurrent, reading and writing cannot be concurrent, and writing and writing cannot be concurrent.

This is the core rule of read-write lock.


2. Why is the ordinary Mutex not elegant enough in the "read more and less" scenario?

This question is especially worth thinking about.

1) Ordinary Mutex treats "read" and "write" equally

For example, you have a cache, configuration table, product information map or blacklist collection.

Most of the time, what threads do may just:

  • Check if a key is there
  • Read the current configuration value
  • Make a judgment based on the shared Map

There are very few moments to really modify data.

If you use a normal Mutex at this time, no matter who comes, you have to serialize:

  • thread a read
  • thread b read
  • thread c or read
  • But they all have to line up

This will make the system throughput down.

2) "Reading operation safety" is not equal to "Reading operation is free"

Some people will say, then I just don't lock it, just read the head office, right?

Can't.

Because "reading more and writing less" does not mean that "writing does not exist".

As long as the write thread may be updating the shared data, the read thread may still read:

  • middle state
  • inconsistent state
  • Objects that have not been released yet
  • Abnormal results during structural modification

So the question is not "whether to protect the read", but:

Can multiple pure reading threads be less blocking each other under the premise of ensuring correctness?

Read-write lock is answering this question.


3. How to cooperate with the read lock and write lock? Memorize the rules first

There are not many rules for read-write lock, but it must be very clear.

1) Read locks can be shared

If no threads currently hold write locks, multiple threads can hold read locks at the same time.

That is:

  • thread a read
  • Thread B also reads
  • thread c or read

They can come in together.

2) Write locks must be exclusive

If there is a thread to modify the shared data, then after it gets the write lock, other threads cannot enter the relevant critical section at the same time.

That is:

  • When writing, other writing is not allowed
  • When writing, it is not allowed to read in

Because the write operation is most afraid of being seen incomplete by others during the modification process.

3) As long as there is a write lock, subsequent readings usually have to wait

This is a place that many people do not adapt to at first.

They will think:

"I just read it, why can't I get in?"

The reason is simple:

The write operation is in progress, and the data may be in the process of change.

If you put it in at this time, the consistency protection is destroyed.

4) Whether it is allowed to jump in queues depends on the implementation strategy

The most common implementation in Java is ReentrantReadWriteLock.

It supports:

  • unfair mode
  • Fair Mode

In different modes, the queuing experience of reading and writing threads will be different, and will be discussed separately later.


Fourth, the most common implementation: ReentrantReadWriteLock How to use it?

The most common read-write lock implementation in Java is:

ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
Lock readLock = rwLock.readLock();
Lock writeLock = rwLock.writeLock();

You can understand it as:

  • A total read-write lock object
  • Remove two "view locks" from the inside
    • read lock
    • Write lock

Then lock them according to the type of operation.

1) Read operation example

public class ConfigStore {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();
    private final Lock writeLock = rwLock.writeLock();
    private final Map<String, String> config = new HashMap<>();

    public String get(String key) {
        readLock.lock();
        try {
            return config.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public void put(String key, String value) {
        writeLock.lock();
        try {
            config.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }
}

In this example:

  • get() Just read, so take the reading lock
  • put() Will change the data, so take the write lock

The effect of this is:

  • Multiple get() can be executed concurrently
  • put() Exclusive when executing
  • put() and get() will not penetrate concurrently

This is the most basic usage.


5. Why is it so common in cache, configuration, and dictionary scenarios?

Because these scenarios are in line with their strengths:

  • High frequency of reading
  • Low frequency of writing
  • Read operations are usually faster
  • Shared data requires consistency protection

Typical examples include:

  • local cache
  • Configuration Center Client Cache
  • rule table
  • routing table
  • Snapshot of user permissions
  • Collection of black and white list
  • Read more and write less memory index

A very common reality judgment:

If 95% of your system's requests are just a query cache, and 5% is to flush the cache, it is usually not cost-effective to make all 95% of the read threads queue each other.

The value of read-write lock is here.


6. But note: not all "read more and write less" must be suitable for read-write lock

This is a very important sentence.

After many people learn read-write lock, they will subconsciously feel that:

As long as you read more than write, you should immediately replace it with ReadWriteLock.

This is not right.

Because read-write lock is not free, it also has costs.

1) The lock itself is more complex and has higher management overhead

Compared with a normal Mutex, read-write lock needs to be maintained:

  • Reader count
  • Writer's Exclusive Status
  • More complex wakeup and queuing logic

If the critical section is very small and the data structure is very simple, then these extra overhead may offset the concurrent gains.

2) If the writing is not rare, the income will decline rapidly

As long as the write operation is a little more frequent, the reading thread will still be blocked often.

At this point you will find:

  • Once the lock is written, the reading still has to stop
  • The system will still have obvious serialization
  • The complexity has increased, but the throughput may not be significantly improved

3) If the read operation itself is particularly short, the competitive advantage of the lock may not be obvious

For example, just reading a simple field, the operation time is extremely low.

At this time, even if read concurrency is allowed, the time saved really may not be significant.

4) If the data structure itself already has a more suitable concurrent scheme, it may not be necessary to write read-write lock by yourself

For example in some scenarios:

  • ConcurrentHashMap
  • atoms
  • Copy-on-write ideas
  • Immutable object snapshot

Might be better than manually maintaining a Read-Write lock.

Therefore, the judging standard is not the four words "read more and write less", but:

Whether the read operation really blocks each other is serious, and whether the blocking is worthy of a more complex synchronization mechanism.


7. What does reentrance mean? Why ReentrantReadWriteLock There is also Reentrant in the name

frontal ReentrantLock It has already been mentioned "reentrant".

Review here again:

Reentrant means: after the same thread has already obtained a lock, you can get the lock again without locking yourself.

In ReentrantReadWriteLock , this feature still exists.

For example, when the same thread holds a write lock, calling another method that also needs a write lock will not be directly deadlocked.

This makes hierarchical calls more secure.

But in read-write lock, there are two more noteworthy behaviors:

  • The write lock holder can obtain the read lock again
  • Read lock owners usually cannot directly safely upgrade to write locks

It will be said separately later.


8. What is a lock downgrade? Why is it a common pattern

The word lock downgrade will be a bit convoluted at first sight.

It actually means:

The thread updates the data while holding the write lock. It then acquires the read lock before releasing the write lock, so it can continue accessing the data as a reader.

The order is usually:

  1. get write lock
  2. Modify shared data
  3. Get read lock
  4. release write lock
  5. Continue to read the result as a read lock

Why do you do this?

Because in some scenarios, after updating the shared state, the thread wants to continue to make a read-only logic based on "the stable result just after the update".

If you directly release the write lock and then take the read lock again, you may be inserted by others to change the data.

Lock downgrades can avoid this window problem.

Example

writeLock.lock();
try {
    // 更新共享数据
    updateData();

    readLock.lock();
} finally {
    writeLock.unlock();
}

try {
    // 继续读取刚刚更新后的稳定结果
    useData();
} finally {
    readLock.unlock();
}

This is the typical downgrade:

  • write -> read

This direction is generally allowed and reasonable.


Nine, why is the lock upgrade dangerous? Why is "read lock upgrade to write lock" is usually not recommended

The so-called lock upgrade means:

  • The thread takes the read lock first
  • Read as you read and find that you need to modify the data
  • Then I want to directly obtain the write lock without releasing the read lock.

It is easy to think this way when many people write cache logic for the first time.

But this direction is often very dangerous and may even lead directly to deadlock or long wait.

Why?

Because the write lock is exclusive, and you are still holding a read lock in your own hand.

If there are other read threads in the system that also hold read locks, then everyone is reading, and no one makes way to make way, and the upgrade is easy to get stuck.

So the common advice is:

Don't expect smooth upgrades from read locks to write locks.

A more stable approach is usually:

  • Release the read lock first
  • re-competitive write lock
  • Recheck the conditions after getting the write lock

Why "recheck the conditions"?

Because you release the read lock until you get the write lock again, the data may have been changed by others.

This idea is the same as many classic rules in concurrency:

As long as the lock is released in the middle, it must be admitted that the state may change.


10. How to understand fair locks and unfair locks in read-write lock?

ReentrantReadWriteLock and ReentrantLock Likewise, a fair/unfair policy is also supported.

1) Unfair mode

The default is generally unfair.

Features are:

  • Feeding is usually higher
  • Threads do not necessarily strictly follow the queuing to obtain locks
  • Stronger body efficiency

2) Fair mode

The Fair Mode emphasizes more:

  • Who will wait first, who will take first
  • Reduce the risk that some threads cannot get locks for a long time

But fairness often means more stringent queuing and more scheduling costs, and throughput may fall.

In read-write lock, a common concern is write thread hunger.

For example, there has been a continuous influx of new read threads. If the scheduling strategy is not handled well, the write thread may not wait for the opportunity for a long time.

This is also why the specific use of the fair model depends on business pressure testing, rather than determined by feeling.


11. An example more like a real project: cache lazy loading

Let's take a look at a very classic scene:

  • Most requests just read the cache
  • When the cache misses, it needs to be loaded and written back

Many people will first react as:

  • Read lock check first
  • If not, upgrade to a write lock

But as mentioned earlier, the upgrade is dangerous.

A more reasonable way to write is usually a "dual check" style:

public class CacheService {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();
    private final Lock writeLock = rwLock.writeLock();
    private final Map<String, String> cache = new HashMap<>();

    public String get(String key) {
        readLock.lock();
        try {
            String value = cache.get(key);
            if (value != null) {
                return value;
            }
        } finally {
            readLock.unlock();
        }

        writeLock.lock();
        try {
            String value = cache.get(key);
            if (value == null) {
                value = loadFromDb(key);
                cache.put(key, value);
            }
            return value;
        } finally {
            writeLock.unlock();
        }
    }

    private String loadFromDb(String key) {
        return "mock-" + key;
    }
}

The most critical here is the second check:

String value = cache.get(key);
if (value == null) {
    value = loadFromDb(key);
    cache.put(key, value);
}

Because from the release read lock to the write lock, there may have been other threads to write the data in.

If you don't re-examine, it is easy to repeatedly load, repeatedly write, and even cause a logical error.


12. Common pitfalls with read-write locks

1) Write the "read operation" as the operation that will modify the state

For example, a method surface is called get(), but secretly inside:

  • update counter
  • Write a log to a shared structure
  • Modify cache timestamp

At this point it is no longer pure reading.

If you still take the read lock, the logic is not safe.

So one of the premise of using read-write lock is:

You must be clear enough about the boundaries of "reading" and "write".

2) Forget in finally mid-release lock

This and ReentrantLock Likewise, it is basic discipline.

lock.lock();
try {
    // 业务逻辑
} finally {
    lock.unlock();
}

Don't try to save trouble.

3) Error try lock upgrade

This has been said before, it is a high frequency pit.

  • Don't rashly go to get the lock in the reading lock
  • If you really want to write, just release the reading lock and re-competate
  • Recheck the status after getting the write lock

4) The read-write ratio is not suitable at all, but the read-write lock is hard

If you write a lot, or the critical section is very short, the read-write lock is often less profitable, and it makes the code more difficult to maintain.

5) Mistakenly think that it must be better than synchronized or ReentrantLock Fast

There is no such absolute relationship.

Concurrency tools are not "naturally more advanced and naturally faster".

Only:

  • Scenario mismatch
  • Competitive model is not suitable
  • Are the results of the stress test good?

13. When should it be used? ReadWriteLock? Give you a practical judgment

My own judgment order is usually as follows:

1) First ask: Does sharing data really need lock protection?

If you can use immutable objects, threads to close, and message passing, it is often simpler.

2) Ask again: Is reading significantly more than writing?

It's not "a little more", but obviously more.

3) Ask again: Is multiple read threads blocking each other, has it become a performance problem?

If it is not a bottleneck at all, don't rush to increase the complexity.

4) Question again: Can ready-made concurrent containers be solved?

For example:

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • AtomicReference

When you can directly use the ready-made solution, you usually do not rub the lock first.

5) Is it worth it to ask: If you have to control the read-write boundary yourself, is read-write lock worth it?

This is the time to really fit it.


14. Final summary: The value of read-write lock is not "more advanced", but "more fit access mode"

Take the core conclusion of this article.

ReadWriteLock It's not that "normal locks can't protect shared data", but:

The ordinary lock is too one-size-fits-all, and it serializes the pure reading operation that could have been concurrent.

So when your scenario meets:

  • Shared data needs protection
  • read far more than write
  • Mutex between read threads has brought significant costs

Then the read-write lock will be very valuable.

But don't deify it either.

It is not the master key for concurrent performance.

If the access pattern does not match, or the ready-made concurrent containers are more suitable, the hard read-write lock will only make the code more complicated.

In one sentence:

Read-write lock is not to make the lock "more powerful", but to make the synchronization strategy more like the access structure in real business.

In the next article, we continue to move forward and talk about a concurrent tool that is easy to be curious and easily misused:

StampedLock After all ReadWriteLock Where is the strong? Why does optimistic reading sound beautiful, and you have to be extra careful when using it?