ReentrantLock源码分析

属性

重入锁是基于AQS实现的,它提供了公平锁和非公平锁两个版本的实现。 

public class ReentrantLock implements Lock, java.io.Serializable {
    
    /***************公平锁和非公平锁*****************/
    
    //锁(该类核心)
    private final Sync sync;
    //非公平锁版本
    static final class NonfairSync extends Sync{……}
    //公平锁版本
    static final class FairSync extends Sync{……}

    /**
     * 默认使用非公平锁
     */
    public ReentrantLock() {
        sync = new NonfairSync();
    }

    /**
     * 手动指定公平策略
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }    

}

非公平锁和公平锁两个类都是内部类,而ReentrantLock中只引入Sync类型的sync,面向接口编程。实际使用哪个版本则由构造器决定,默认使用非公平锁,也可以在构造时手动指定。

构造器

    /**
     * 构造器:默认非公平,等价于ReentrantLock(false)
     */
    public ReentrantLock() {
        //默认使用非公平锁
        sync = new NonfairSync();
    }

    /**
     * 构造器:使用指定的公平策略
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

加锁(非公平版)-lock

因为默认使用非公平版本,我们先跟踪一下非公平版的lock()源码,看看是如何实现的

public void lock() {
    sync.lock();
}

//内部类NonfairSync中的lock方法
final void lock() {
    //先使用CAS方式【抢占一次】锁。若成功则独占该锁(将AQS的state由0改为1,并将当前线程设置锁拥有者)
    if (compareAndSetState(0, 1))
        //将当前线程设置为锁拥有者(exclusiveOwnerThread表示“持有锁的线程”)
        setExclusiveOwnerThread(Thread.currentThread());
    else//失败,则加入等待队列(入队前会先进行一次获取锁操作)
        acquire(1);
}

//父类AQS类中的acquire方法
public final void acquire(int arg) {
    //入队前,此时锁可能已被释放,先尝试一次获取锁的操作。
    //获取失败,则将线程包装成节点,加入等待队列尾部,完成后中断线程。
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

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


final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    //锁没被线程持有,则竞争该锁,成功则将state由0改为1,并将当前线程标记为锁拥有者
    if (c == 0) {
        if (compareAndSetState(0, acquires)) {//CAS方式获取锁
            //将当前线程标记为锁拥有者
            setExclusiveOwnerThread(current);
            return true;
        }
    }//锁已经被持有
    //锁已被线程持有,则统计重入次数。
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;//state值+1(传进来的是1)
        if (nextc < 0) // overflow
            throw new Error("Maximum lock count exceeded");
        //修改state【不需要使用CAS来修改state,相当于偏向锁】
        setState(nextc);
        return true;
    }
    return false;
}

加锁(公平版)-lock

再来跟踪一下公平版本的lock()方法源码

/**
 * 没有抢占操作,直接进入等待队列排队(公平)
 */
final void lock() {
    acquire(1);
}

//父类AQS类中的acquire方法
public final void acquire(int arg) {
    //入队前,此时锁可能已被释放,先尝试一次获取锁的操作。
    //获取失败,则将线程包装成节点,加入等待队列尾部,完成后中断线程。
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

/**
 * tryAcquire公平版本。
 */
protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    //锁没被线程持有
    if (c == 0) {        
        //【快捷方式】先判断是否有前驱节点(因为队列是FIFO,前驱等待时间更长,既然公平,就要保证先来先获取)
        //若无前驱,则通过CAS操作获取,成功则将state由0改为1,并设置当前线程拥有该锁。
        if (!hasQueuedPredecessors() &&
            compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    //锁已由当前线程持有,则统计重入次数
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }//锁由其它线程持有
    return false;
}

释放锁-unlock

unlock方法实现都是相同的。

public void unlock() {
    sync.release(1);
}
    
protected final boolean tryRelease(int releases) {
    int c = getState() - releases;
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    //锁状态已为0,则可以释放锁了。(state累加了多少次,就要对应的减多少次,才能把锁解开)
    if (c == 0) {
        free = true;//释放锁成功
        setExclusiveOwnerThread(null);//设置锁拥有者为null
    }
    //更新state
    setState(c);
    return free;
}

总结

1.锁的状态变化?

锁由state表示,初始状态为0。线程初次获取到锁,则将state由0改为1,锁拥有者为当前线程。线程重入获取到锁,依旧将state状态加1,每次重入都加1。

退出临界区state就减1,最终直至0,锁释放,锁拥有者为null。

2.非公平锁获取锁和公平获取锁过程的区别?

非公平lock:

①先进行一次CAS抢占获取锁,成功则返回,失败则进入等待队列。

②入队列前,可能此时锁已被释放,先进行一次CAS获取锁,成功则返回。失败将线程封装成节点加入队列尾部,并中断线程。

公平lock:

①直接进入等待队列。

②入队列前,可能此时锁已被释放,先进行一次获取锁操作。过程是:判断是否有前驱节点,如果有前驱,根据FIFO必然前驱更应优先获取锁,因此获取锁失败。若无前驱,则再通过CAS获取锁,成功则返回,失败将线程封装成节点加入队列尾部,并中断线程。

参考:

五月的仓颉 ReentrantLock实现原理深入探究 

活在梦里 AQS源码解读

原文地址:https://www.cnblogs.com/rouqinglangzi/p/9909688.html