ReentrantReadWriteLock的readerShouldBlock与apparentlyFirstQueuedIsExclusive 深入理解读锁的非公平实现

前言

ReentrantReadWriteLock的读锁或写锁的获取过程中,在CAS修改同步器状态之前,会使用readerShouldBlockwriterShouldBlock来根据当前公平模式和当前同步队列来得到当前线程是否可以继续尝试获得锁(CAS修改同步器状态)。

readerShouldBlockwriterShouldBlock封装掉了当前的公平模式(公平还是非公平的),无论是在独占锁的获取过程还是在共享锁的获取过程中,你会发现,公平实现与非公平实现的差异在于,公平实现会调用hasQueuedPredecessors,非公平实现则不会。

所以,XXXShouldBlockhasQueuedPredecessors之上进行了封装,公平实现下,XXXShouldBlock肯定会去调用hasQueuedPredecessors的。

JUC框架 系列文章目录

writerShouldBlock的非公平实现

我们首先看写锁的ShouldBlock的两种实现。

//非公平实现
        final boolean writerShouldBlock() {
            return false; // writers can always barge
        }
//公平实现
        final boolean writerShouldBlock() {
            return hasQueuedPredecessors();
        }

可见writerShouldBlock在非公平实现下,是直接返回false的。这是一种完全的非公平实现。

当一个线程想要获得写锁成功时,只有当前ReentrantReadWriteLock的写锁没有被其他线程持有,且ReentrantReadWriteLock的读锁没有被任意线程持有(注意这里是任意线程,包括自己线程持有读锁)。所以writerShouldBlock的非公平实现直接返回false,代表你尽管去非公平地尝试,反正想抢写锁成功,条件是很苛刻的。

readerShouldBlock的非公平实现

可见readerShouldBlock的实现并不是直接返false,而是调用apparentlyFirstQueuedIsExclusive。这不是一种完全的非公平实现,但这样做是有它的道理的。

//非公平实现
        final boolean readerShouldBlock() {
            /* As a heuristic to avoid indefinite writer starvation,
             * block if the thread that momentarily appears to be head
             * of queue, if one exists, is a waiting writer.  This is
             * only a probabilistic effect since a new reader will not
             * block if there is a waiting writer behind other enabled
             * readers that have not yet drained from the queue.
             */
            return apparentlyFirstQueuedIsExclusive();
        }
//公平实现
        final boolean readerShouldBlock() {
            return hasQueuedPredecessors();
        }

    /**
     * Returns {@code true} if the apparent first queued thread, if one
     * exists, is waiting in exclusive mode.  If this method returns
     * {@code true}, and the current thread is attempting to acquire in
     * shared mode (that is, this method is invoked from {@link
     * #tryAcquireShared}) then it is guaranteed that the current thread
     * is not the first queued thread.  Used only as a heuristic in
     * ReentrantReadWriteLock.
     */
    final boolean apparentlyFirstQueuedIsExclusive() {
        Node h, s;
        return (h = head) != null &&
            (s = h.next)  != null &&
            !s.isShared()         &&
            s.thread != null;
    }

As a heuristic to avoid indefinite writer starvation, block if the thread that momentarily appears to be head of queue, if one exists, is a waiting writer. This is only a probabilistic effect since a new reader will not block if there is a waiting writer behind other enabled readers that have not yet drained from the queue.

翻译过来就是,这只是一种启发式地避免写锁无限等待的做法,它在遇到同步队列的head后继为写锁节点时,会让readerShouldBlock返回true代表新来的读锁(new reader)需要阻塞等待这个head后继。但只是一定概率下能起到作用,如果同步队列的head后继是一个读锁,之后才是写锁的话,readerShouldBlock就肯定会返回false了。

new reader意思就是,线程第一次来尝试获取读锁。

写锁无限等待 indefinite writer starvation

在这里插入图片描述

首先解释一下indefinite writer starvation,上图中,写锁节点作为head后继阻塞等待中。

考虑readerShouldBlock的现有实现的话,写锁节点只需要等待线程AB释放读锁后,就可以获得到写锁了。而线程CDE作为new reader,不会去尝试获取读锁,而是将自己包装成读锁节点排在写锁节点的后面。这个具体的流程,请查看ReentrantReadWriteLock源码解析读锁的获取章节内容里面对fullTryAcquireShared函数的讲解,我们只需要知道readerShouldBlock返回了true,代表读锁获取应该阻塞,如果这个读锁是个new reader。

//非公平实现
        final boolean readerShouldBlock() {
            return false;
        }

但考虑readerShouldBlock如上代码这样实现的话,线程CDE即使作为new reader,因为读读不互斥,所以也会去获取到读锁。这下好了,写锁节点需要等待线程ABCDE释放读锁后,才可以获得到写锁了。

heuristic启发式地防止new reader

在这里插入图片描述
但尽管readerShouldBlock是这样的非公平实现,也无法防止上图第二种情况的new reader的获取读锁动作,所以说这只是一定概率下防止new reader获取读锁,但有概率的防止总比啥都不做强。

总结

  • readerShouldBlock的非公平实现,并不是完全的非公平实现(即直接返回false)。
  • readerShouldBlock的不完全的非公平实现,是为了防止写锁无限等待。
  • readerShouldBlock在一定概率下,防止了new reader的读锁获取动作,转而让new reader去sync queue中排队。
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
### 回答1: 以下是使用Java编写的ReentrantLock和ReentrantReadWriteLock的代码示例: ReentrantLock示例: ```java import java.util.concurrent.locks.ReentrantLock; public class Counter { private int count = 0; private ReentrantLock lock = new ReentrantLock(); public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } public void decrement() { lock.lock(); try { count--; } finally { lock.unlock(); } } public int getCount() { return count; } } ``` ReentrantReadWriteLock示例: ```java import java.util.concurrent.locks.ReentrantReadWriteLock; public class Cache { private Object data = null; private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); public Object getData() { lock.readLock().lock(); try { return data; } finally { lock.readLock().unlock(); } } public void setData(Object data) { lock.writeLock().lock(); try { this.data = data; } finally { lock.writeLock().unlock(); } } } ``` 在这些示例中,ReentrantLock和ReentrantReadWriteLock都被用于控制共享资源的访问。使用lock()方法获取锁,使用unlock()方法释放锁。在ReentrantReadWriteLock示例中,readLock()和writeLock()方法被用于获取读锁和写锁,以控制对共享数据的读和写访问。 ### 回答2: ReentrantLock(可重入锁)和ReentrantReadWriteLock(可重入读写锁)是Java并发包中提供的两种锁机制。它们都是可重入锁,意味着同一个线程可以多次获取同一个锁。 首先,我们来看一下ReentrantLock的代码例子。在下面的示例中,有两个线程分别尝试获取同一把锁,并对共享资源进行操作。 ```java import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockExample { private static final ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) { Thread thread1 = new Thread(() -> { lock.lock(); try { // 对共享资源进行操作 System.out.println("Thread 1 is accessing the shared resource."); } finally { lock.unlock(); } }); Thread thread2 = new Thread(() -> { lock.lock(); try { // 对共享资源进行操作 System.out.println("Thread 2 is accessing the shared resource."); } finally { lock.unlock(); } }); thread1.start(); thread2.start(); } } ``` 上述代码中,两个线程分别通过lock()方法获取锁,并在finally块中使用unlock()方法释放锁。这就确保了同一时间只能有一个线程访问共享资源。 接下来,我们来看一下ReentrantReadWriteLock的代码例子。与ReentrantLock不同,ReentrantReadWriteLock可以支持多个读线程同时访问共享资源,但只允许一个写线程进行写操作。 ```java import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReentrantReadWriteLockExample { private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static final ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); private static final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); private static int sharedResource = 0; public static void main(String[] args) { Thread reader1 = new Thread(() -> { readLock.lock(); try { // 读取共享资源 System.out.println("Reader 1 is reading the value: " + sharedResource); } finally { readLock.unlock(); } }); Thread reader2 = new Thread(() -> { readLock.lock(); try { // 读取共享资源 System.out.println("Reader 2 is reading the value: " + sharedResource); } finally { readLock.unlock(); } }); Thread writer = new Thread(() -> { writeLock.lock(); try { // 修改共享资源 sharedResource = 100; System.out.println("Writer is updating the value to: " + sharedResource); } finally { writeLock.unlock(); } }); reader1.start(); reader2.start(); writer.start(); } } ``` 在上述代码中,我们使用了readLock()和writeLock()方法来获取读锁和写锁,然后通过lock()方法进行加锁,通过unlock()方法进行解锁。这样保证了在写操作时,不允许其他线程同时进行读或写操作。 以上是ReentrantLock和ReentrantReadWriteLock的简单代码例子,它们在多线程并发操作中提供了可靠的锁机制,确保数据的安全性和一致性。 ### 回答3: ReentrantLock和ReentrantReadWriteLock是Java.util.concurrent包中的两个线程同步工具。它们都实现Lock接口,可以用于对共享资源进行线程安全的访问。 首先,我们来看一下ReentrantLock的代码示例: ```java import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockExample { private ReentrantLock lock = new ReentrantLock(); public void printMessage(String message) { lock.lock(); try { // 访问共享资源 System.out.println(message); } finally { lock.unlock(); // 释放锁 } } } ``` 在上面的示例中,我们创建了一个ReentrantLock对象lock,并将它用于保护printMessage方法中的临界区。lock.lock()用于获取锁,如果锁已被其他线程占用,则当前线程等待。然后在try块中访问共享资源,最后在finally块中使用lock.unlock()来释放锁。 接下来,我们看一下ReentrantReadWriteLock的代码示例: ```java import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReentrantReadWriteLockExample { private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private String data = "Shared data"; public String readData() { rwLock.readLock().lock(); try { // 读取共享数据 return data; } finally { rwLock.readLock().unlock(); // 释放读锁 } } public void writeData(String input) { rwLock.writeLock().lock(); try { // 更新共享数据 data = input; } finally { rwLock.writeLock().unlock(); // 释放写锁 } } } ``` 在上述示例中,我们创建了一个ReentrantReadWriteLock对象rwLock,并将它用于保护readData和writeData方法中的临界区。rwLock.readLock()用于获取读锁,rwLock.writeLock()用于获取写锁。多个线程可以同时获取读锁,但只有一个线程可以获取写锁。除有线程持有写锁,否则其他线程可以同时获取读锁。在读操作中,我们使用读锁保护共享数据的只读访问,而在写操作中,我们使用写锁保护共享数据的更新。 以上是ReentrantLock和ReentrantReadWriteLock的简单代码示例,它们可以帮助我们在多线程环境中实现资源的安全访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值