【JDK1.8源码阅读】ReentrantLock源码实现分析整理(六)


重入锁ReentrantLock实现了Lock接口,即实现了加解锁操作的基本API,在此基础上,ReentrantLock提供以下特性:

  1. 支持同一线程对资源的重复加锁,即同一线程重复调用lock方法不会堵塞,但后续解锁次数需要和加锁次数同步,才能真正意义地释放锁。
  2. 支持获取锁时的公平和非公平性选择。

在ReentrantLock,有3个非常核心的内部类:Sync,FairSync,NonfairSync,其中Sync继承自AbstractQueuedSynchronizer,提供了队列同步器的各个公平/非公平加解锁操作的核心实现,而FairSync和NonfairSync继承自Sync,主要实现了lock和tryAcquire方法。
类关系如下:
image

Sync类实现

先看Sync类的基本实现:

abstract static class Sync extends AbstractQueuedSynchronizer {
    // 序列号
    private static final long serialVersionUID = -5179523762034025860L;
    
    // 获取锁,抽象方法,供ReentrantLock实现了Lock
    abstract void lock();
    
    // 非公平方式获取
    final boolean nonfairTryAcquire(int acquires) {
        // 当前线程
        final Thread current = Thread.currentThread();
        // 获取状态
        int c = getState();
        if (c == 0) { // 表示没有线程正在竞争该锁
            if (compareAndSetState(0, acquires)) { // 比较并设置状态成功,状态0表示锁没有被占用
                // 设置当前线程独占
                setExclusiveOwnerThread(current); 
                return true; // 成功
            }
        }
        else if (current == getExclusiveOwnerThread()) { // 当前线程拥有该锁,这里无需考虑并发,因为只有当前线程能进入
            int nextc = c + acquires; // 增加重入次数
            if (nextc < 0) // overflow
                throw new Error("Maximum lock count exceeded");
            // 设置状态
            setState(nextc); 
            // 成功
            return true; 
        }
        // 失败
        return false;
    }
    
    // 如果当前线程非持同步状态线程,会抛已成,否则递减状态值,直到状态值为0才真正释放锁
    protected final boolean tryRelease(int releases) {
        int c = getState() - releases;
        if (Thread.currentThread() != getExclusiveOwnerThread()) // 当前线程不为独占线程
            throw new IllegalMonitorStateException(); // 抛出异常
        // 后续操作只有持同步状态线程才能操作,故无需考虑并发问题
        // 释放标识
        boolean free = false; 
        if (c == 0) {
            free = true;
            // 已经释放,清空独占
            setExclusiveOwnerThread(null); 
        }
        // 设置标识
        setState(c); 
        return free; 
    }
    
    // 判断资源是否被当前线程占有
    protected final boolean isHeldExclusively() {
        return getExclusiveOwnerThread() == Thread.currentThread();
    }

    // 生成一个条件对象,用于多个和当前锁关联的线程的堵塞/唤醒交互操作
    final ConditionObject newCondition() {
        return new ConditionObject();
    }

    // Methods relayed from outer class
    // 返回资源的占用线程
    final Thread getOwner() {        
        return getState() == 0 ? null : getExclusiveOwnerThread();
    }
    // 返回状态值
    final int getHoldCount() {            
        return isHeldExclusively() ? getState() : 0;
    }

    // 资源是否被占用,不一定是本线程占用
    final boolean isLocked() {        
        return getState() != 0;
    }

    /**
     * 反序列化时特别注意将状态值设为0
     */
    // 自定义反序列化逻辑
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
    }
}

在Sync类的加解锁操作定义中,一个突出特点是根据state来判定重入次数,如果state=0,说明没有线程获取同步状态,当前线程获取后,设置当前线程为独占线程(在子类lock方法实现),后续当前线程可不断重入加解锁,通过修改state值实现;修改后state不为0,则其他线程不能获取锁。

NonfairSync 非公平锁实现

NonfairSync非公平锁的核心实现逻辑在lock方法,会用cas,尝试将state值从0改到1,如果成功,则设置当前线程为独占线程,否则说明锁被占用,调用同步器acquire方法堵塞直到拿到同步状态。代码实现如下:

// 非公平锁
static final class NonfairSync extends Sync {
    // 版本号
    private static final long serialVersionUID = 7316153563782823691L;

    // 获得锁
    final void lock() {
        // 比较并设置状态成功,状态0表示锁没有被占用
        if (compareAndSetState(0, 1)) 
            // 把当前线程设置独占了锁
            setExclusiveOwnerThread(Thread.currentThread());
        else // 锁已经被占用,或者set失败
            // 以独占模式获取对象,忽略中断
            acquire(1); 
    }

    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

非公平锁的非公平性主要体现在nonfairTryAcquire里当state=0时,直接尝试compareAndSetState(0, acquires),即如果当前没有线程占有锁,当前线程直接通过cas指令占有锁,而不管当前线程在队列的哪个位置。

FairSync 公平锁实现

FairSync公平锁完整主要实现了tryAcquire方法,对于lock方法,只是简单调用acquire(1)函数,核心实现逻辑放在tryAcquire()中,通过同步器分析直到,在调用acquire方法里,会优先调用tryAcquire()方法。公平锁的实现逻辑在tryAcquire()中完成。

先看下源码实现

static final class FairSync extends Sync {
    // 版本序列化
    private static final long serialVersionUID = -3000897897090466540L;

    final void lock() {
        // 以独占模式获取对象,忽略中断
        acquire(1);
    }

    // 尝试公平获取锁
    protected final boolean tryAcquire(int acquires) {
        // 获取当前线程
        final Thread current = Thread.currentThread();
        // 获取状态
        int c = getState();
        if (c == 0) { // 状态为0
            if (!hasQueuedPredecessors() &&
                compareAndSetState(0, acquires)) { // 不存在已经等待更久的线程并且比较并且设置状态成功
                // 设置当前线程独占
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        else if (current == getExclusiveOwnerThread()) { // 状态不为0,即资源已经被线程占据
            // 下一个状态
            int nextc = c + acquires;
            if (nextc < 0) // 超过了int的表示范围
                throw new Error("Maximum lock count exceeded");
            // 设置状态
            setState(nextc);
            return true;
        }
        return false;
    }
}

整体实现类似非公平锁的nonfairTryAcquire实现,主要区别是当状态为0时,判断当前线程是否为等待时间最久的,如果是则更新为独占线程,并返回加锁成功,否则返回失败。

判定当前线程是否为等待时间最久的在函数hasQueuedPredecessors中实现,实现逻辑也较为简单,因为线程是按照先后顺序进入同步队列的,所以同步队列最前面的节点必定是等待最久的节点。

具体源码实现如下:

public final boolean hasQueuedPredecessors() {
    // 本地缓存头尾节点
    Node t = tail; 
    Node h = head;
    Node s;
    // 判断头节点的下一个节点是否为当前节点
    return h != t &&
        ((s = h.next) == null || s.thread != Thread.currentThread());
}

ReentrantLock锁API实现

ReentrantLock实现了Lock接口,所有加解锁的实现细节都在Sync、NonfairSync、FairSync等内部类中实现,主要提供了于用户友好交互的锁操作API,具体实现如下:

public class ReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    
    private final Sync sync;
    
    /**
     * 默认创建一个非公平锁
     */
    public ReentrantLock() {
        sync = new NonfairSync();
    }

    /**
     * 可以传入fair=true来创建一个公平锁
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }
    
    /**
     * 堵塞获取锁
     */
    public void lock() {
        sync.lock();
    }

    /**
     * 堵塞获取锁,可被打断
     */
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    /**
     * 尝试加锁,无论成功失败立即返回
     */
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

    /**
     * 在超时时间内堵塞加锁,加锁成功返回true,超时返回false,被打断则抛异常
     */
    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    /**
     * 尝试解锁,注意如果非当前线程占有锁会抛IllegalMonitorStateException
     */
    public void unlock() {
        sync.release(1);
    }

    /**
     * 初始化一个条件对象
     */
    public Condition newCondition() {
        return sync.newCondition();
    }

    /**
     * 如果当前线程持有锁,返回state,表示重入数,否则返回0
     */
    public int getHoldCount() {
        return sync.getHoldCount();
    }

    /**
     * 判断是否被当前线程持有锁
     */
    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

    /**
     * 判断是否已加锁,不一定是当前线程
     */
    public boolean isLocked() {
        return sync.isLocked();
    }

    /**
     * 判断当前是否为公平锁
     */
    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    /**
     * 获取锁所属线程,如果没有返回null
     */
    protected Thread getOwner() {
        return sync.getOwner();
    }

    /**
     * 判断同步队列中是否有堵塞同步线程
     */
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /**
     * 判断指定线程是否在同步队列中
     */
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    /**
     * 获取同步队列中的等待节点数
     */
    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    /**
     * 获取同步队列中的所有等待线程
     */
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    /**
     * 判断是否有条件对象的等待者
     */
    public boolean hasWaiters(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * 获取条件对象中等待队列长度
     */
    public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * 获取条件对象的等待队列中的所有等待线程
     */
    protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    public String toString() {
        Thread o = sync.getOwner();
        return super.toString() + ((o == null) ?
                                   "[Unlocked]" :
                                   "[Locked by thread " + o.getName() + "]");
    }

参考

  1. https://www.cnblogs.com/leesf456/p/5383609.html
  2. Java并发编程的艺术
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值